_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q246300 | Poser.generateFromURI | validation | public function generateFromURI($string)
{
$badge = Badge::fromURI($string);
return $this->getRenderFor($badge->getFormat())->render($badge);
} | php | {
"resource": ""
} |
q246301 | Badge.fromURI | validation | public static function fromURI($URI)
{
$regex = '/^(([^-]|--)+)-(([^-]|--)+)-(([^-]|--)+)\.(svg|png|gif|jpg)$/';
$match = array();
if (1 != preg_match($regex, $URI, $match) && (7 != count($match))) {
throw new \InvalidArgumentException('The URI given is not a valid URI'.$URI);
}
$subject = $match[1];
$status = $match[3];
$color = $match[5];
$format = $match[7];
return new self($subject, $status, $color, $format);
} | php | {
"resource": ""
} |
q246302 | GDTextSizeCalculator.calculateWidth | validation | public function calculateWidth($text, $size = self::TEXT_SIZE)
{
$size = $this->convertToPt($size);
$box = imagettfbbox($size, 0, $this->fontPath, $text);
return round(abs($box[2] - $box[0]) + self::SHIELD_PADDING_EXTERNAL + self::SHIELD_PADDING_INTERNAL, 1);
} | php | {
"resource": ""
} |
q246303 | Curl.output | validation | public function output():string {
// Buffer will be null before exec is called...
if(is_null($this->buffer)) {
$this->exec();
}
curl_close($this->ch);
// ...But will always be a string after exec is called, even if empty.
if(strlen($this->buffer) === 0) {
throw new NoOutputException();
}
return $this->buffer;
} | php | {
"resource": ""
} |
q246304 | Curl.outputJson | validation | public function outputJson(
int $depth = 512,
int $options = 0
) {
$json = json_decode(
$this->output(),
false,
$depth,
$options
);
if(is_null($json)) {
$errorMessage = json_last_error_msg();
throw new JsonDecodeException($errorMessage);
}
return $json;
} | php | {
"resource": ""
} |
q246305 | Curl.exec | validation | public function exec():string {
ob_start();
$response = curl_exec($this->ch);
$this->buffer = ob_get_contents();
ob_end_clean();
if(false === $response) {
throw new CurlException($this->error());
}
if(true === $response) {
$response = $this->buffer;
}
return $response;
} | php | {
"resource": ""
} |
q246306 | Curl.getInfo | validation | public function getInfo(int $opt):string {
if($opt <= 0) {
throw new CurlException(
"Option must be greater than zero, "
. $opt
. " given."
);
}
return curl_getinfo($this->ch, $opt);
} | php | {
"resource": ""
} |
q246307 | Curl.init | validation | public function init(string $url = null):void {
$this->ch = curl_init($url);
CurlObjectLookup::add($this);
} | php | {
"resource": ""
} |
q246308 | Curl.setOpt | validation | public function setOpt(int $option, $value):bool {
return curl_setopt($this->ch, $option, $value);
} | php | {
"resource": ""
} |
q246309 | CurlShare.setOpt | validation | public function setOpt(int $option, string $value):bool {
return curl_share_setopt($this->sh, $option, $value);
} | php | {
"resource": ""
} |
q246310 | CurlMulti.infoRead | validation | public function infoRead(int &$msgsInQueue = null):?CurlMultiInfoInterface {
$info = curl_multi_info_read(
$this->mh,
$msgsInQueue
);
if(!$info) {
return null;
}
return new CurlMultiInfo($info);
} | php | {
"resource": ""
} |
q246311 | HtmlHelper.determineHeaderTags | validation | protected function determineHeaderTags($topLevel, $depth)
{
$desired = range((int) $topLevel, (int) $topLevel + ((int) $depth - 1));
$allowed = [1, 2, 3, 4, 5, 6];
return array_map(function($val) { return 'h'.$val; }, array_intersect($desired, $allowed));
} | php | {
"resource": ""
} |
q246312 | HtmlHelper.traverseHeaderTags | validation | protected function traverseHeaderTags(\DOMDocument $domDocument, $topLevel, $depth)
{
$xpath = new \DOMXPath($domDocument);
$xpathQuery = sprintf(
"//*[%s]",
implode(' or ', array_map(function($v) {
return sprintf('local-name() = "%s"', $v);
}, $this->determineHeaderTags($topLevel, $depth)))
);
$nodes = [];
foreach ($xpath->query($xpathQuery) as $node) {
$nodes[] = $node;
}
return new \ArrayIterator($nodes);
} | php | {
"resource": ""
} |
q246313 | TocGenerator.getHtmlMenu | validation | public function getHtmlMenu($markup, $topLevel = 1, $depth = 6, RendererInterface $renderer = null)
{
if ( ! $renderer) {
$renderer = new ListRenderer(new Matcher(), [
'currentClass' => 'active',
'ancestorClass' => 'active_ancestor'
]);
}
return $renderer->render($this->getMenu($markup, $topLevel, $depth));
} | php | {
"resource": ""
} |
q246314 | Create.createController | validation | private function createController(): void
{
$aFields = $this->getArguments();
$aCreated = [];
try {
$aModels = array_filter(explode(',', $aFields['MODEL_NAME']));
foreach ($aModels as $sModel) {
$aFields['MODEL_NAME'] = $sModel;
$this->oOutput->write('Creating controller <comment>' . $sModel . '</comment>... ');
// Validate model exists by attempting to load it
Factory::model($sModel, $aFields['MODEL_PROVIDER']);
// Check for existing controller
$sPath = static::CONTROLLER_PATH . $sModel . '.php';
if (file_exists($sPath)) {
throw new ControllerExistsException(
'Controller "' . $sModel . '" exists already at path "' . $sPath . '"'
);
}
$this->createFile($sPath, $this->getResource('template/controller.php', $aFields));
$aCreated[] = $sPath;
$this->oOutput->writeln('<info>done!</info>');
}
} catch (\Exception $e) {
$this->oOutput->writeln('<error>failed!</error>');
// Clean up created models
if (!empty($aCreated)) {
$this->oOutput->writeln('<error>Cleaning up - removing newly created controllers</error>');
foreach ($aCreated as $sPath) {
@unlink($sPath);
}
}
throw $e;
}
} | php | {
"resource": ""
} |
q246315 | ApiRouter.outputSetFormat | validation | public function outputSetFormat($sFormat)
{
if (static::isValidFormat($sFormat)) {
$this->sOutputFormat = strtoupper($sFormat);
return true;
}
return false;
} | php | {
"resource": ""
} |
q246316 | ApiRouter.writeLog | validation | public function writeLog($sLine)
{
if (!is_string($sLine)) {
$sLine = print_r($sLine, true);
}
$sLine = ' [' . $this->sModuleName . '->' . $this->sMethod . '] ' . $sLine;
$this->oLogger->line($sLine);
} | php | {
"resource": ""
} |
q246317 | DefaultController.getIndex | validation | public function getIndex($aData = [], $iPage = null, $iPerPage = null)
{
$oInput = Factory::service('Input');
$oItemModel = Factory::model(
static::CONFIG_MODEL_NAME,
static::CONFIG_MODEL_PROVIDER
);
if (is_null($iPage)) {
$iPage = (int) $oInput->get('page') ?: 1;
}
if (is_null($iPerPage)) {
$iPerPage = static::CONFIG_MAX_ITEMS_PER_PAGE;
}
$aResults = $oItemModel->getAll(
$iPage,
$iPerPage,
$aData
);
// @todo (Pablo - 2018-06-24) - Paging
$oResponse = Factory::factory('ApiResponse', 'nails/module-api');
$oResponse->setData(array_map([$this, 'formatObject'], $aResults));
return $oResponse;
} | php | {
"resource": ""
} |
q246318 | DefaultController.getId | validation | public function getId($aData = [])
{
$sIds = '';
$oInput = Factory::service('Input');
$oHttpCodes = Factory::service('HttpCodes');
if (!empty($oInput->get('id'))) {
$sIds = $oInput->get('id');
}
if (!empty($oInput->get('ids'))) {
$sIds = $oInput->get('ids');
}
$aIds = explode(',', $sIds);
$aIds = array_filter($aIds);
$aIds = array_unique($aIds);
if (count($aIds) > self::CONFIG_MAX_ITEMS_PER_REQUEST) {
throw new ApiException(
'You can request a maximum of ' . self::CONFIG_MAX_ITEMS_PER_REQUEST . ' items per request',
$oHttpCodes::STATUS_BAD_REQUEST
);
}
// --------------------------------------------------------------------------
$oItemModel = Factory::model(
static::CONFIG_MODEL_NAME,
static::CONFIG_MODEL_PROVIDER
);
$aResults = $oItemModel->getByIds($aIds, $aData);
if ($oInput->get('id')) {
$oItem = reset($aResults);
$mData = $oItem ? $this->formatObject($oItem) : null;
} else {
$mData = array_map([$this, 'formatObject'], $aResults);
}
$oResponse = Factory::factory('ApiResponse', 'nails/module-api');
$oResponse->setData($mData);
return $oResponse;
} | php | {
"resource": ""
} |
q246319 | DefaultController.getSearch | validation | public function getSearch($aData = [])
{
$oInput = Factory::service('Input');
$oHttpCodes = Factory::service('HttpCodes');
$oItemModel = Factory::model(
static::CONFIG_MODEL_NAME,
static::CONFIG_MODEL_PROVIDER
);
$sKeywords = $oInput->get('search') ?: $oInput->get('keywords');
$iPage = (int) $oInput->get('page');
if (strlen($sKeywords) < static::CONFIG_MIN_SEARCH_LENGTH) {
throw new ApiException(
'Search term must be ' . static::CONFIG_MIN_SEARCH_LENGTH . ' characters or longer.',
$oHttpCodes::STATUS_BAD_REQUEST
);
}
$oResult = $oItemModel->search(
$sKeywords,
$iPage,
static::CONFIG_MAX_ITEMS_PER_PAGE,
$aData
);
$oResponse = Factory::factory('ApiResponse', 'nails/module-api');
$oResponse->setData(array_map([$this, 'formatObject'], $oResult->data));
return $oResponse;
} | php | {
"resource": ""
} |
q246320 | DefaultController.postRemap | validation | public function postRemap()
{
$oUri = Factory::service('Uri');
// Test that there's not an explicit method defined for this
$sMethod = 'post' . ucfirst($oUri->segment(4));
if (method_exists($this, $sMethod)) {
return $this->$sMethod();
}
$oInput = Factory::service('Input');
$oHttpCodes = Factory::service('HttpCodes');
$oItemModel = Factory::model(
static::CONFIG_MODEL_NAME,
static::CONFIG_MODEL_PROVIDER
);
// Validate fields
$aFields = $oItemModel->describeFields();
$aValid = [];
$aInvalid = [];
foreach ($aFields as $oField) {
if (in_array($oField->key, static::CONFIG_POST_IGNORE_FIELDS)) {
continue;
}
$aValid[] = $oField->key;
}
$aPost = $oInput->post();
foreach ($aPost as $sKey => $sValue) {
if (!in_array($sKey, $aValid)) {
$aInvalid[] = $sKey;
}
}
if (!empty($aInvalid)) {
throw new ApiException(
'The following arguments are invalid: ' . implode(', ', $aInvalid),
$oHttpCodes::STATUS_BAD_REQUEST
);
}
$iItemId = (int) $oUri->segment(4);
if ($iItemId) {
$oItem = $oItemModel->getById($iItemId);
if (empty($oItem)) {
throw new ApiException(
'Item does not exist',
$oHttpCodes::STATUS_NOT_FOUND
);
} elseif (!$oItemModel->update($iItemId, $aPost)) {
throw new ApiException(
'Failed to update item. ' . $oItemModel->lastError(),
$oHttpCodes::STATUS_INTERNAL_SERVER_ERROR
);
} elseif (classUses($oItemModel, 'Nails\Common\Traits\Caching')) {
$oItemModel->disableCache();
}
$oItem = $oItemModel->getById($iItemId);
if (classUses($oItemModel, 'Nails\Common\Traits\Caching')) {
$oItemModel->enableCache();
}
} else {
$oItem = $oItemModel->create($aPost, true);
}
$oResponse = Factory::factory('ApiResponse', 'nails/module-api');
$oResponse->setData($this->formatObject($oItem));
return $oResponse;
} | php | {
"resource": ""
} |
q246321 | CrudController.postIndex | validation | public function postIndex()
{
$oInput = Factory::service('Input');
$oHttpCodes = Factory::service('HttpCodes');
$this->userCan(static::ACTION_CREATE);
/**
* First check the $_POST superglobal, if that's empty then fall back to
* the body of the request assuming it is JSON.
*/
$aData = $oInput->post();
if (empty($aData)) {
$sData = stream_get_contents(fopen('php://input', 'r'));
$aData = json_decode($sData, JSON_OBJECT_AS_ARRAY) ?: [];
}
$aData = $this->validateUserInput($aData);
$iItemId = $this->oModel->create($aData);
if (empty($iItemId)) {
throw new ApiException(
'Failed to create resource. ' . $this->oModel->lastError(),
$oHttpCodes::STATUS_INTERNAL_SERVER_ERROR
);
}
$oItem = $this->oModel->getById($iItemId, static::CONFIG_LOOKUP_DATA);
$oResponse = Factory::factory('ApiResponse', 'nails/module-api');
$oResponse->setData($this->formatObject($oItem));
return $oResponse;
} | php | {
"resource": ""
} |
q246322 | CrudController.putRemap | validation | public function putRemap($sMethod)
{
// Test that there's not an explicit method defined for this action
$oUri = Factory::service('Uri');
$sMethod = 'put' . ucfirst($oUri->segment(4));
if (method_exists($this, $sMethod)) {
return $this->$sMethod();
}
// --------------------------------------------------------------------------
$oItem = $this->lookUpResource();
if (!$oItem) {
throw new ApiException('Resource not found', 404);
}
$this->userCan(static::ACTION_UPDATE, $oItem);
$oHttpCodes = Factory::service('HttpCodes');
// Read from php:://input as using PUT; expecting a JSONobject as the payload
$sData = stream_get_contents(fopen('php://input', 'r'));
$aData = json_decode($sData, JSON_OBJECT_AS_ARRAY) ?: [];
$aData = $this->validateUserInput($aData, $oItem);
if (!$this->oModel->update($oItem->id, $aData)) {
throw new ApiException(
'Failed to update resource. ' . $this->oModel->lastError(),
$oHttpCodes::STATUS_INTERNAL_SERVER_ERROR
);
}
return Factory::factory('ApiResponse', 'nails/module-api');
} | php | {
"resource": ""
} |
q246323 | CrudController.deleteRemap | validation | public function deleteRemap($sMethod)
{
// Test that there's not an explicit method defined for this action
$oUri = Factory::service('Uri');
$sMethod = 'put' . ucfirst($oUri->segment(4));
if (method_exists($this, $sMethod)) {
return $this->$sMethod();
}
// --------------------------------------------------------------------------
$oHttpCodes = Factory::service('HttpCodes');
$oItem = $this->lookUpResource();
if (!$oItem) {
throw new ApiException(
'Resource not found',
$oHttpCodes::STATUS_NOT_FOUND
);
}
$this->userCan(static::ACTION_DELETE, $oItem);
if (!$this->oModel->delete($oItem->id)) {
throw new ApiException(
'Failed to delete resource. ' . $this->oModel->lastError(),
$oHttpCodes::STATUS_INTERNAL_SERVER_ERROR
);
}
return Factory::factory('ApiResponse', 'nails/module-api');
} | php | {
"resource": ""
} |
q246324 | CrudController.lookUpResource | validation | protected function lookUpResource($aData = [], $iSegment = 4)
{
$oUri = Factory::service('Uri');
$sIdentifier = $oUri->segment($iSegment);
// Handle requests for expansions
$oInput = Factory::service('Input');
$aData = array_merge(static::CONFIG_LOOKUP_DATA, $aData);
$aExpansions = array_filter((array) $oInput->get('expand'));
if ($aExpansions) {
if (!array_key_exists('expand', $aData)) {
$aData['expand'] = [];
}
$aData['expand'] = array_merge($aData['expand'], $aExpansions);
}
switch (static::CONFIG_LOOKUP_METHOD) {
case 'ID':
return $this->oModel->getById($sIdentifier, $aData);
break;
case 'SLUG':
return $this->oModel->getBySlug($sIdentifier, $aData);
break;
case 'TOKEN':
return $this->oModel->getByToken($sIdentifier, $aData);
break;
}
} | php | {
"resource": ""
} |
q246325 | CrudController.validateUserInput | validation | protected function validateUserInput($aData, $oItem = null)
{
$aOut = [];
$aFields = $this->oModel->describeFields();
$aKeys = array_unique(
array_merge(
array_keys($aFields),
arrayExtractProperty($this->oModel->getExpandableFields(), 'trigger')
)
);
$aValidKeys = array_diff($aKeys, static::IGNORE_FIELDS_WRITE);
foreach ($aValidKeys as $sValidKey) {
$oField = getFromArray($sValidKey, $aFields);
if (array_key_exists($sValidKey, $aData)) {
$aOut[$sValidKey] = getFromArray($sValidKey, $aData);
}
// @todo (Pablo - 2018-08-20) - Further validation using the $oField->validation rules
}
return $aOut;
} | php | {
"resource": ""
} |
q246326 | CrudController.buildUrl | validation | protected function buildUrl($iTotal, $iPage, $iPageOffset)
{
$aParams = [
'page' => $iPage + $iPageOffset,
];
if ($aParams['page'] <= 0) {
return null;
} elseif ($aParams['page'] === 1) {
unset($aParams['page']);
}
$iTotalPages = ceil($iTotal / static::CONFIG_PER_PAGE);
if (!empty($aParams['page']) && $aParams['page'] > $iTotalPages) {
return null;
}
$sUrl = site_url() . uri_string();
if (!empty($aParams)) {
$sUrl .= '?' . http_build_query($aParams);
}
return $sUrl;
} | php | {
"resource": ""
} |
q246327 | CmdTransaction.startTransaction | validation | public function startTransaction(): bool
{
if ($this->isInTransaction)
throw new AlreadyInTransactionException();
$this->isInTransaction = $this->executeDirect('START TRANSACTION');
return $this->isInTransaction;
} | php | {
"resource": ""
} |
q246328 | CmdTransaction.commit | validation | public function commit(): bool
{
if (!$this->isInTransaction)
throw new NotInTransactionException();
$this->isInTransaction = false;
return $this->executeDirect('COMMIT');
} | php | {
"resource": ""
} |
q246329 | TQuery.queryMap | validation | public function queryMap($key = 0, $value = 1)
{
$fetchMode = $this->resolveFetchMode(is_string($key) || is_string($value));
$result = $this->execute();
$map = [];
try
{
while ($row = $result->fetch($fetchMode))
{
if (!isset($row[$key]) || !key_exists($value, $row))
throw new MySqlException(
"Key '$key' or Value '$value' columns not found in the query result: " .
implode(array_keys($row)));
$map[$row[$key]] = $row[$value];
}
}
// Free resources when generator released before reaching the end of the iteration.
finally
{
$result->closeCursor();
}
return $map;
} | php | {
"resource": ""
} |
q246330 | TQuery.queryMapRow | validation | public function queryMapRow($key = 0, $removeColumnFromRow = false)
{
$fetchMode = $this->resolveFetchMode(is_string($key));
$result = $this->execute();
$map = [];
try
{
while ($row = $result->fetch($fetchMode))
{
if (!isset($row[$key]))
throw new MySqlException(
"Key '$key' column not found in the query result: " .
implode(array_keys($row)));
if ($removeColumnFromRow)
{
$map[$row[$key]] = $row;
unset($map[$row[$key]][$key]);
}
else
{
$map[$row[$key]] = $row;
}
}
}
// Free resources when generator released before reaching the end of the iteration.
finally
{
$result->closeCursor();
}
return $map;
} | php | {
"resource": ""
} |
q246331 | FileConnector.execute | validation | public function execute($path)
{
if (!file_exists($path) || !is_readable($path))
throw new SquidException("The file at [$path] is unreadable or doesn't exists");
$data = file_get_contents($path);
$result = $this->connector
->bulk()
->add($data)
->executeAll();
return (bool)$result;
} | php | {
"resource": ""
} |
q246332 | CmdDirect.asScalarSubQuery | validation | private function asScalarSubQuery($callback, $default = false)
{
$sql = $this->sql;
$this->sql = $callback($sql);
$result = $this->queryScalar(null);
$this->sql = $sql;
return (is_null($result) ? $default : $result);
} | php | {
"resource": ""
} |
q246333 | CmdCreate.assemble | validation | public function assemble()
{
$command =
'CREATE ' .
$this->getPartIfSet(self::PART_TEMP) .
'TABLE ' .
$this->getPartIfSet(self::PART_IF_NOT_EXIST) .
$this->parts[self::PART_DB] . $this->parts[self::PART_NAME];
if ($this->parts[self::PART_LIKE])
{
return $command . ' ' . $this->parts[self::PART_LIKE];
}
if (!$this->columnsList->isEmpty())
{
$command .= '(';
$columns = $this->columnsList->assemble();
$keys = $this->indexes->assemble();
$combined = array_merge($columns, $keys);
$command .= implode(',', $combined);
$command .= ') ' .
$this->getPartIfSet(self::PART_ENGINE, 'ENGINE=') .
$this->getPartIfSet(self::PART_CHARSET, 'CHARSET=') .
$this->getPartIfSet(self::PART_CHARSET, 'AUTO_INCREMENT=') .
$this->getPartIfSet(self::PART_COMMENT, 'COMMENT=');
}
if ($this->parts[self::PART_AS])
{
$command .= " {$this->getAsExpression()}";
}
return $command;
} | php | {
"resource": ""
} |
q246334 | CmdController.rotate | validation | public function rotate($tableA, $tableB)
{
$tableT = $tableA . '_' . time() . '_' . rand(0, 1000000);
return $this->rename([
$tableB => $tableT,
$tableA => $tableB,
$tableT => $tableA
]);
} | php | {
"resource": ""
} |
q246335 | CmdMultiQuery.executeIterator | validation | public function executeIterator()
{
$result = $this->execute();
if (!$result)
throw new MySqlException('Could not execute multiset query!');
while (true)
{
yield new StatementResult($result);
if (!$result->nextRowset())
{
$this->checkForError($result);
break;
}
}
} | php | {
"resource": ""
} |
q246336 | CmdUpsert.getDefaultParts | validation | protected function getDefaultParts()
{
if (!isset(CmdUpsert::$DEFAULT))
{
CmdUpsert::$DEFAULT = parent::getDefaultParts();
CmdUpsert::$PART_SET = count(CmdUpsert::$DEFAULT);
CmdUpsert::$DEFAULT[CmdUpsert::$PART_SET] = false;
}
return CmdUpsert::$DEFAULT;
} | php | {
"resource": ""
} |
q246337 | SelectCombiner.queryExists | validation | public function queryExists()
{
foreach ($this->selects as $select)
{
$result = $select->queryExists();
if (is_null($result) || $result)
{
return $result;
}
}
return false;
} | php | {
"resource": ""
} |
q246338 | CmdInsert.appendByField | validation | private function appendByField($values)
{
$fixed = array();
foreach ($this->fields as $field)
{
$fixed[] = $values[$field];
}
return $this->appendByPosition($fixed);
} | php | {
"resource": ""
} |
q246339 | CmdInsert.appendByPosition | validation | private function appendByPosition($values)
{
$this->setPart(CmdInsert::PART_AS, false);
if (!$this->placeholder)
$this->placeholder = Assembly::placeholder(count($values), true);
return $this->appendPart(
CmdInsert::PART_VALUES,
$this->placeholder,
$values
);
} | php | {
"resource": ""
} |
q246340 | CmdInsert.into | validation | public function into($table, array $fields = null)
{
$this->setPart(CmdInsert::PART_INTO, $table);
if (!is_null($fields))
{
$this->placeholder = false;
$this->fields = $fields;
}
return $this;
} | php | {
"resource": ""
} |
q246341 | CmdInsert.values | validation | public function values($values)
{
if (isset($values[0]))
return $this->appendByPosition($values);
$this->fixDefaultValues($values);
if (!$this->fields)
{
$this->placeholder = false;
$this->fields = array_keys($values);
return $this->appendByPosition(array_values($values));
}
return $this->appendByField($values);
} | php | {
"resource": ""
} |
q246342 | CmdInsert.valuesExp | validation | public function valuesExp($expression, $bind = false)
{
return $this->appendPart(
CmdInsert::PART_VALUES,
$expression,
$bind
);
} | php | {
"resource": ""
} |
q246343 | CmdInsert.asSelect | validation | public function asSelect(ICmdSelect $select)
{
$this->setPart(CmdInsert::PART_VALUES, false);
return $this->setPart(CmdInsert::PART_AS, $select->assemble(), $select->bind());
} | php | {
"resource": ""
} |
q246344 | Assembly.appendSet | validation | public static function appendSet($values, $forceExist = false)
{
if ($forceExist && !$values)
throw new SquidException('SET clause must be present for this type of command!');
return Assembly::append('SET', $values, ', ');
} | php | {
"resource": ""
} |
q246345 | AbstractCommand.execute | validation | public function execute()
{
if (is_null($this->conn))
throw new SquidException("Can't execute query, implicitly created without connection!");
$cmd = $this->assemble();
$bind = $this->bind();
return $this->conn->execute($cmd, $bind);
} | php | {
"resource": ""
} |
q246346 | CmdUpdate.limit | validation | public function limit($from, $count): IWithLimit
{
return $this->setPart(CmdUpdate::PART_LIMIT, true, ($from ? array($from, $count) : $count));
} | php | {
"resource": ""
} |
q246347 | CmdUpdate._set | validation | public function _set($exp, $bind = false)
{
return $this->appendPart(CmdUpdate::PART_SET, $exp, $bind);
} | php | {
"resource": ""
} |
q246348 | MySql.createConnector | validation | public function createConnector($name)
{
$connector = new MySqlConnector($name);
$connector->setConnection($this->getNewConnection($name));
return $connector;
} | php | {
"resource": ""
} |
q246349 | TWithLimit.appendDesc | validation | private function appendDesc(&$column): void
{
if (is_array($column))
{
foreach ($column as &$col)
{
$col = "$col DESC";
}
}
else
{
$column = ["$column DESC"];
}
} | php | {
"resource": ""
} |
q246350 | TWithLimit.orderBy | validation | public function orderBy($column, $type = OrderBy::ASC): IWithLimit
{
if ($type == OrderBy::DESC)
{
$this->appendDesc($column);
}
else if (!is_array($column))
{
$column = [$column];
}
return $this->_orderBy($column);
} | php | {
"resource": ""
} |
q246351 | PartsCommand.appendBind | validation | private function appendBind($part, $bind)
{
if ($bind === false) return $this;
if (!is_array($bind)) $bind = [$bind];
if (!$this->bind[$part])
{
$this->bind[$part] = $bind;
}
else
{
$this->bind[$part] = array_merge($this->bind[$part], $bind);
}
return $this;
} | php | {
"resource": ""
} |
q246352 | PartsCommand.appendPart | validation | protected function appendPart($part, $sql, $bind = false)
{
if (!is_array($sql)) $sql = [$sql];
if (!$this->parts[$part])
{
$this->parts[$part] = $sql;
}
else
{
$this->parts[$part] = array_merge($this->parts[$part], $sql);
}
return $this->appendBind($part, $bind);
} | php | {
"resource": ""
} |
q246353 | PartsCommand.setPart | validation | protected function setPart($part, $sql, $bind = false)
{
$this->parts[$part] = $sql;
if (is_array($bind)) $this->bind[$part] = $bind;
else if ($bind === false) $this->bind[$part] = false;
else $this->bind[$part] = [$bind];
return $this;
} | php | {
"resource": ""
} |
q246354 | Writer.writeQTime | validation | public function writeQTime($timestamp)
{
if ($timestamp instanceof \DateTime) {
$msec = $timestamp->format('H') * 3600000 +
$timestamp->format('i') * 60000 +
$timestamp->format('s') * 1000 +
(int)($timestamp->format('0.u') * 1000);
} else {
$msec = round(($timestamp - strtotime('midnight', (int)$timestamp)) * 1000);
}
$this->writeUInt($msec);
} | php | {
"resource": ""
} |
q246355 | Writer.conv | validation | private function conv($str)
{
// prefer mb_convert_encoding if available
if ($this->supportsExtMbstring) {
return mb_convert_encoding($str, 'UTF-16BE', 'UTF-8');
}
// otherwise match each UTF-8 character byte sequence, manually convert
// it to its Unicode code point and then encode as UTF-16BE byte sequence.
return preg_replace_callback('/./su', function ($m) {
if (!isset($m[0][1])) {
// U+0000 - U+007F single byte ASCII/UTF-8 character
return "\x00" . $m[0];
}
if (isset($m[0][3])) {
// U+10000 - U+10FFFF uses four UTF-8 bytes and 4 UTF-16 bytes
// get code point and convert to higher and lower surrogate
$code = ((ord($m[0][0]) & 0x07) << 18) + ((ord($m[0][1]) & 0x3F) << 12) + ((ord($m[0][2]) & 0x3F) << 6) + (ord($m[0][3]) & 0x3F);
return pack('nn', ($code - 0x10000 >> 10) | 0xD800, ($code & 0x03FF) | 0xDC00);
}
if (isset($m[0][2])) {
// U+0800 - U+FFFF uses three UTF-8 bytes
$code = ((ord($m[0][0]) & 0x0F) << 12) + ((ord($m[0][1]) & 0x3F) << 6) + (ord($m[0][2]) & 0x3F);
} else {
// U+0080 - U+07FF uses two UTF-8 bytes
$code = ((ord($m[0][0]) & 0x1F) << 6) + (ord($m[0][1]) & 0x3F);
}
return chr($code >> 8) . chr($code & 0xFF);
}, $str);
} | php | {
"resource": ""
} |
q246356 | Publisher.submitArticle | validation | public function submitArticle(Article $article): \One\Model\Article
{
$responseArticle = $this->post(
self::ARTICLE_ENDPOINT,
$this->normalizePayload(
$article->getCollection()
)
);
$responseArticle = json_decode($responseArticle, true);
$article->setId((string) $responseArticle['data']['id']);
foreach ($article->getPossibleAttachment() as $field) {
if ($article->hasAttachment($field)) {
foreach ($article->getAttachmentByField($field) as $attachment) {
$this->submitAttachment(
$article->getId(),
$attachment,
$field
);
}
}
}
return $article;
} | php | {
"resource": ""
} |
q246357 | Publisher.submitAttachment | validation | public function submitAttachment(string $idArticle, Model $attachment, string $field): array
{
return json_decode(
$this->post(
$this->getAttachmentEndPoint($idArticle, $field),
$this->normalizePayload(
$attachment->getCollection()
)
),
true
);
} | php | {
"resource": ""
} |
q246358 | Publisher.deleteArticle | validation | public function deleteArticle(string $idArticle): ?string
{
$articleOnRest = $this->getArticle($idArticle);
if (! empty($articleOnRest)) {
$articleOnRest = json_decode($articleOnRest, true);
if (isset($articleOnRest['data'])) {
foreach (Article::getDeleteableAttachment() as $field) {
if (isset($articleOnRest['data'][$field])) {
foreach ($articleOnRest['data'][$field] as $attachment) {
if (isset($attachment[$field . '_order'])) {
$this->deleteAttachment($idArticle, $field, $attachment[$field . '_order']);
}
}
}
}
}
return $this->delete(
$this->getArticleWithIdEndPoint($idArticle)
);
}
} | php | {
"resource": ""
} |
q246359 | Publisher.deleteAttachment | validation | public function deleteAttachment(string $idArticle, string $field, string $order): string
{
return $this->delete(
$this->getAttachmentEndPoint($idArticle, $field) . "/${order}"
);
} | php | {
"resource": ""
} |
q246360 | Publisher.assessOptions | validation | private function assessOptions(array $options): void
{
$defaultOptions = [
'rest_server' => self::REST_SERVER,
'auth_url' => self::AUTHENTICATION,
'max_attempt' => self::DEFAULT_MAX_ATTEMPT,
'default_headers' => [
'Accept' => 'application/json',
],
];
$this->options = new Collection(
array_merge(
$defaultOptions,
$options
)
);
if (isset($options['access_token'])) {
$this->setAuthorizationHeader($options['access_token']);
}
if (isset($options['recycle_token']) && is_callable($options['recycle_token'])) {
$this->recycleToken(
$options['recycle_token']
);
}
if (isset($options['token_saver']) && is_callable($options['token_saver'])) {
$this->setTokenSaver(
$options['token_saver']
);
}
$this->httpClient = new Client([
'base_uri' => $this->options->get('rest_server'),
]);
} | php | {
"resource": ""
} |
q246361 | Publisher.requestGate | validation | private function requestGate(string $method, string $path, array $header = [], array $body = [], array $options = []): string
{
if (empty($this->accessToken)) {
$this->renewAuthToken();
}
$request = new \GuzzleHttp\Psr7\Request(
$method,
$path,
array_merge(
$this->options->get('default_headers'),
$header
),
$this->createBodyForRequest(
$this->prepareMultipartData($body)
)
);
return (string) $this->sendRequest($request);
} | php | {
"resource": ""
} |
q246362 | Publisher.sendRequest | validation | private function sendRequest(RequestInterface $request, int $attempt = 0): \Psr\Http\Message\StreamInterface
{
if ($attempt >= $this->options->get('max_attempt')) {
throw new \Exception('MAX attempt reached for ' . $request->getUri() . ' with payload ' . (string) $request);
}
try {
$response = $this->httpClient->send(
$request,
[
'allow_redirects' => false,
'synchronous' => true,
'curl' => [
CURLOPT_FORBID_REUSE => true,
CURLOPT_MAXCONNECTS => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYSTATUS => false,
],
]
);
if ($response->getStatusCode() === 200) {
return $response->getBody();
}
return $this->sendRequest($request, $attempt++);
} catch (ClientException $err) {
if ($err->getResponse()->getStatusCode() === 401 && $request->getRequestTarget() !== self::AUTHENTICATION) {
$this->renewAuthToken();
return $this->sendRequest($request, $attempt++);
}
throw $err;
} catch (\Throwable $err) {
throw $err;
}
} | php | {
"resource": ""
} |
q246363 | Publisher.setAuthorizationHeader | validation | private function setAuthorizationHeader(string $accessToken): self
{
$this->accessToken = $accessToken;
$this->options->set(
'default_headers',
array_merge(
$this->options->get('default_headers'),
[
'Authorization' => 'Bearer ' . $accessToken,
]
)
);
return $this;
} | php | {
"resource": ""
} |
q246364 | Publisher.getAttachmentEndPoint | validation | private function getAttachmentEndPoint(string $idArticle, string $field): string
{
return $this->replaceEndPointId(
$idArticle,
$this->attachmentUrl[$field]
);
} | php | {
"resource": ""
} |
q246365 | SimpleXml.castToArray | validation | private function castToArray($input): array
{
$result = array();
foreach ($input as $key => $value) {
$result[$key] = $this->castValue($value);
}
return $result;
} | php | {
"resource": ""
} |
q246366 | AbstractKernel.serve | validation | public function serve()
{
foreach ($this->dispatchers as $dispatcher) {
if ($dispatcher->canServe()) {
ContainerScope::runScope($this->container, [$dispatcher, 'serve']);
return;
}
}
throw new BootException("Unable to locate active dispatcher.");
} | php | {
"resource": ""
} |
q246367 | AbstractKernel.init | validation | public static function init(
array $directories,
EnvironmentInterface $environment = null,
bool $handleErrors = true
): ?self {
if ($handleErrors) {
ExceptionHandler::register();
}
$core = new static(new Container(), $directories);
$core->container->bindSingleton(
EnvironmentInterface::class,
$environment ?? new Environment()
);
try {
ContainerScope::runScope($core->container, function () use ($core) {
$core->bootload();
$core->bootstrap();
});
} catch (\Throwable $e) {
ExceptionHandler::handleException($e);
return null;
}
return $core;
} | php | {
"resource": ""
} |
q246368 | Reader.readQTime | validation | public function readQTime()
{
$msec = $this->readUInt();
$time = strtotime('midnight') + $msec / 1000;
$dt = \DateTime::createFromFormat('U.u', sprintf('%.6F', $time));
$dt->setTimezone(new \DateTimeZone(date_default_timezone_get()));
return $dt;
} | php | {
"resource": ""
} |
q246369 | Reader.readQDateTime | validation | public function readQDateTime()
{
$day = $this->readUInt();
$msec = $this->readUInt();
/*$isUtc = */ $this->readBool();
if ($day === 0 && $msec === 0xFFFFFFFF) {
return null;
}
// days since unix epoche in seconds plus msec in seconds
$time = ($day - 2440588) * 86400 + $msec / 1000;
$dt = \DateTime::createFromFormat('U.u', sprintf('%.6F', $time));
$dt->setTimezone(new \DateTimeZone(date_default_timezone_get()));
return $dt;
} | php | {
"resource": ""
} |
q246370 | Reader.conv | validation | private function conv($str)
{
// prefer mb_convert_encoding if available
if ($this->supportsExtMbstring) {
return mb_convert_encoding($str, 'UTF-8', 'UTF-16BE');
}
// Otherwise convert each byte pair to its Unicode code point and
// then manually encode as UTF-8 bytes.
return preg_replace_callback('/(?:[\xD8-\xDB]...)|(?:..)/s', function ($m) {
if (isset($m[0][3])) {
// U+10000 - U+10FFFF uses four UTF-16 bytes and 4 UTF-8 bytes
// get code point from higher and lower surrogate and convert
list(, $higher, $lower) = unpack('n*', $m[0]);
$code = (($higher & 0x03FF) << 10) + ($lower & 0x03FF) + 0x10000;
return pack(
'c*',
$code >> 18 | 0xF0,
$code >> 12 & 0x3F | 0x80,
$code >> 6 & 0x3F | 0x80,
$code & 0x3F | 0x80
);
}
list(, $code) = unpack('n', $m[0]);
if ($code < 0x80) {
// U+0000 - U+007F encodes as single ASCII/UTF-8 byte
return chr($code);
} elseif ($code < 0x0800) {
// U+0080 - U+07FF encodes as two UTF-8 bytes
return chr($code >> 6 | 0xC0) . chr($code & 0x3F | 0x80);
} else {
// U+0800 - U+FFFF encodes as three UTF-8 bytes
return chr($code >> 12 | 0xE0) . chr($code >> 6 & 0x3F | 0x80) . chr($code & 0x3F | 0x80);
}
return '?';
}, $str);
} | php | {
"resource": ""
} |
q246371 | Uri.withString | validation | protected function withString(string $string, string $name = 'query'): self
{
$string = ltrim((string) $string, '#');
$clone = clone $this;
$clone->{$name} = $this->filterQuery($string);
return $clone;
} | php | {
"resource": ""
} |
q246372 | Uri.filterPort | validation | protected function filterPort(?int $port): ?int
{
if ((integer) $port >= 0 && (integer) $port <= 65535) {
return $port;
}
throw new InvalidArgumentException('Uri port must be null or an integer between 1 and 65535 (inclusive)');
} | php | {
"resource": ""
} |
q246373 | Uri.hasStandardPort | validation | protected function hasStandardPort(): bool
{
return ($this->scheme === 'http' && $this->port === 80) || ($this->scheme === 'https' && $this->port === 443);
} | php | {
"resource": ""
} |
q246374 | FactoryUri.create | validation | public static function create(string $string = ''): \One\Uri
{
if (empty($string)) {
$string = '/';
}
return self::createFromString($string);
} | php | {
"resource": ""
} |
q246375 | FactoryUri.createUri | validation | private static function createUri(string $scheme, string $host, ?int $port, string $user, string $password, string $path, string $query, string $fragment): \One\Uri
{
return new Uri(
$scheme,
$host,
$port,
$path,
$query,
$fragment,
$user,
$password
);
} | php | {
"resource": ""
} |
q246376 | EmailSenderDataBuilder.extract | validation | public function extract(Collection $resources, Closure $callback)
{
foreach ($resources as $resource) {
$callback($resource, ['record' => $resource]);
}
} | php | {
"resource": ""
} |
q246377 | ExceptionHandler.handleShutdown | validation | public static function handleShutdown()
{
if (!empty($error = error_get_last())) {
self::handleException(
new FatalException($error['message'], $error['type'], 0, $error['file'],
$error['line'])
);
}
} | php | {
"resource": ""
} |
q246378 | ExceptionHandler.handleError | validation | public static function handleError($code, $message, $filename = '', $line = 0)
{
throw new \ErrorException($message, $code, 0, $filename, $line);
} | php | {
"resource": ""
} |
q246379 | ExceptionHandler.handleException | validation | public static function handleException(\Throwable $e)
{
if (php_sapi_name() == 'cli') {
$handler = new ConsoleHandler(self::$output);
} else {
$handler = new HtmlHandler(HtmlHandler::INVERTED);
}
// we are safe to handle global exceptions (system level) with maximum verbosity
fwrite(self::$output, $handler->renderException($e, AbstractHandler::VERBOSITY_VERBOSE));
} | php | {
"resource": ""
} |
q246380 | Application.add | validation | public function add($middleware, string $pathConstraint = null): void
{
if (is_string($middleware)) {
$middleware = $this->getContainer()->get($middleware);
}
if (!$middleware instanceof MiddlewareInterface) {
throw new InvalidArgumentException('Middleware must be an instance of ' . MiddlewareInterface::class);
}
$this->middleware[] = new Middleware($middleware, $pathConstraint);
} | php | {
"resource": ""
} |
q246381 | Application.map | validation | public function map(array $methods, string $path, $handler): void
{
if (is_string($handler)) {
$handler = $this->getContainer()->get($handler);
}
$this->router->map($methods, $path, $handler);
} | php | {
"resource": ""
} |
q246382 | Application.run | validation | public function run(): void
{
$request = $request = ServerRequestFactory::fromGlobals();
$response = $this->process($request);
$emitter = $this->getContainer()->has(EmitterInterface::class)
? $this->getContainer()->get(EmitterInterface::class)
: new SapiEmitter();
$emitter->emit($response);
} | php | {
"resource": ""
} |
q246383 | Application.process | validation | public function process(ServerRequestInterface $request): ResponseInterface
{
$filteredMiddleware = $this->middleware;
try {
$request = $this->router->dispatch($request);
$route = $request->getAttribute('route');
$filteredMiddleware = array_filter($filteredMiddleware, function (Middleware $middleware) use ($route) {
return $middleware->executeFor($route);
});
$requestHandler = $route->getHandler();
} catch (HttpException $e) {
$requestHandler = new NextHandler(function () use ($e) {
throw $e;
});
}
$filteredMiddleware = array_map(function (Middleware $middleware) {
return $middleware->getMiddleware();
}, $filteredMiddleware);
$dispatcher = new Stack(
$filteredMiddleware,
$requestHandler
);
return $dispatcher->dispatch($request);
} | php | {
"resource": ""
} |
q246384 | FactoryPhoto.create | validation | public static function create(array $data): \One\Model\Photo
{
$url = self::validateUrl((string) self::checkData($data, 'url', ''));
$ratio = self::validateString((string) self::checkData($data, 'ratio', ''));
$description = self::validateString((string) self::checkData($data, 'description', ''));
$information = self::validateString((string) self::checkData($data, 'information', ''));
return self::createPhoto($url, $ratio, $description, $information);
} | php | {
"resource": ""
} |
q246385 | FactoryPhoto.createPhoto | validation | private static function createPhoto(string $url, string $ratio, string $description, string $information): \One\Model\Photo
{
return new Photo(
$url,
$ratio,
$description,
$information
);
} | php | {
"resource": ""
} |
q246386 | Mailtrap._after | validation | public function _after(\Codeception\TestCase $test)
{
if(isset($this->config['deleteEmailsAfterScenario']) && $this->config['deleteEmailsAfterScenario'])
{
$this->deleteAllEmails();
}
} | php | {
"resource": ""
} |
q246387 | Mailtrap.accessInboxFor | validation | public function accessInboxFor($address)
{
$inbox = array();
$addressPlusDelimiters = '<' . $address . '>';
foreach($this->fetchedEmails as &$email)
{
$email->Headers = $this->getHeaders($email->id)->headers;
if(!isset($email->Headers->bcc))
{
if(strpos($email->Headers->to, $addressPlusDelimiters) || strpos($email->Headers->cc, $addressPlusDelimiters))
{
array_push($inbox, $email);
}
}
else if(strpos($email->Headers->bcc, $addressPlusDelimiters))
{
array_push($inbox, $email);
}
}
$this->setCurrentInbox($inbox);
} | php | {
"resource": ""
} |
q246388 | Mailtrap.getOpenedEmail | validation | protected function getOpenedEmail($fetchNextUnread = FALSE)
{
if($fetchNextUnread || $this->openedEmail == NULL)
{
$this->openNextUnreadEmail();
}
return $this->openedEmail;
} | php | {
"resource": ""
} |
q246389 | Mailtrap.getMostRecentUnreadEmail | validation | protected function getMostRecentUnreadEmail()
{
if(empty($this->unreadInbox))
{
$this->fail('Unread Inbox is Empty');
}
$email = array_shift($this->unreadInbox);
$content = $this->getFullEmail($email->id);
$content->Headers = $this->getHeaders($email->id)->headers;
return $content;
} | php | {
"resource": ""
} |
q246390 | Mailtrap.getFullEmail | validation | protected function getFullEmail($id)
{
try
{
$response = $this->sendRequest('GET', "/api/v1/inboxes/{$this->config['inbox_id']}/messages/{$id}");
}
catch(Exception $e)
{
$this->fail('Exception: ' . $e->getMessage());
}
$fullEmail = json_decode($response->getBody());
return $fullEmail;
} | php | {
"resource": ""
} |
q246391 | Mailtrap.getEmailRecipients | validation | protected function getEmailRecipients($email)
{
$recipients = $email->Headers->to . ' ' .
$email->Headers->cc;
if($email->Headers->bcc != NULL)
{
$recipients .= ' ' . $email->Headers->bcc;
}
return $recipients;
} | php | {
"resource": ""
} |
q246392 | Mailtrap.textAfterString | validation | protected function textAfterString($haystack, $needle)
{
$result = "";
$needleLength = strlen($needle);
if($needleLength > 0 && preg_match("#$needle([^\r\n]+)#i", $haystack, $match))
{
$result = trim(substr($match[0], -(strlen($match[0]) - $needleLength)));
}
return $result;
} | php | {
"resource": ""
} |
q246393 | Mailtrap.sortEmailsByCreationDatePredicate | validation | static function sortEmailsByCreationDatePredicate($emailA, $emailB)
{
$sortKeyA = $emailA->sent_at;
$sortKeyB = $emailB->sent_at;
return ($sortKeyA > $sortKeyB) ? -1 : 1;
} | php | {
"resource": ""
} |
q246394 | Configurable.addConfiguration | validation | public function addConfiguration($configuration, $configure = true)
{
if (!$configuration instanceof ConfigurationInterface) {
$configuration = new Configuration($configuration);
}
$config = $this->getConfiguration();
if ($config instanceof ConfigurationInterface) {
$config->merge($configuration);
}
if ($config === null) {
$config = $configuration;
}
$this->setConfiguration($config, $configure);
} | php | {
"resource": ""
} |
q246395 | Configurable.configure | validation | public function configure()
{
$configuration = $this->getConfiguration();
if ($configuration instanceof ConfigurationInterface) {
$this->configuration->configure($this);
}
} | php | {
"resource": ""
} |
q246396 | Configurable.setConfiguration | validation | public function setConfiguration($configuration, $configure = true)
{
if (!$configuration instanceof ConfigurationInterface) {
$configuration = new Configuration($configuration);
}
unset($this->configuration); // destroy the old one
$this->configuration = $configuration;
if ($configure) {
$this->configure();
}
} | php | {
"resource": ""
} |
q246397 | Memory.getFilename | validation | private function getFilename(string $name): string
{
//Runtime cache
return sprintf(
"%s/%s.%s",
$this->directory,
strtolower(str_replace(['/', '\\'], '-', $name)),
self::EXTENSION
);
} | php | {
"resource": ""
} |
q246398 | Middleware.executeFor | validation | public function executeFor(Route $route): bool
{
if (null === $this->pathConstraint) {
return true;
}
return strpos($route->getPath(), $this->pathConstraint) === 0;
} | php | {
"resource": ""
} |
q246399 | FactoryGallery.create | validation | public static function create(array $data): \One\Model\Gallery
{
$body = self::validateString((string) self::checkData($data, 'body', ''));
$order = self::validateInteger((int) self::checkData($data, 'order', null));
$photo = self::validateUrl((string) self::checkData($data, 'photo', ''));
$source = self::validateUrl((string) self::checkData($data, 'source', ''));
$lead = self::validateString((string) self::checkData($data, 'lead', ''));
return self::createGallery($body, $order, $photo, $source, $lead);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.