_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q240600
|
LongLog.setJobName
|
train
|
public function setJobName($name)
{
if (!is_string($name)) {
throw new InvalidArgumentException('Job name must be a string');
}
$name = trim($name);
$strlen = mb_strlen($name);
if (!$strlen) {
throw new InvalidArgumentException('Job name cannot be empty');
} elseif ($strlen < 2 || $strlen > 255) {
throw new InvalidArgumentException('Job name length must be in range 2-255 characters');
}
$this->jobName = $name;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240601
|
LongLog.setPayload
|
train
|
public function setPayload($data)
{
if (!is_string($data)) {
if (is_array($data)) {
$data = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} else {
$data = serialize($data);
}
}
$maxLength = 255;
if (mb_strlen($data) > $maxLength) {
// Truncate too long payload
$data = mb_substr($data, 0, $maxLength - 3) . '...';
}
$this->payload = $data ? $data : null;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240602
|
LongLog.setDuration
|
train
|
public function setDuration($seconds)
{
$seconds = round($seconds, 3);
if ($seconds < 0 || $seconds > 999999.999) {
throw new InvalidArgumentException('Duration seconds must be in range 0-999999.999');
}
$this->duration = $seconds;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240603
|
FloatObject.round
|
train
|
public function round(int $precision = 0, ?RoundingMode $roundingMode = null): FloatObject
{
if ($roundingMode === null) {
$roundingMode = RoundingMode::HALF_UP();
}
return new static((float) round($this->value, $precision, $roundingMode->value()));
}
|
php
|
{
"resource": ""
}
|
q240604
|
QueryBuilder.setModel
|
train
|
public function setModel($model)
{
$this->model = $model;
$this->from($this->model->metableTable() . ' AS m');
if ($this->model->metableTableSoftDeletes()) {
$this->whereNull('m.' . $this->model->getDeletedAtColumn());
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q240605
|
QueryBuilder.whereAnyMetaId
|
train
|
public function whereAnyMetaId(array $metas)
{
$filters = array();
foreach ($metas as $meta => $data) {
$value = is_array($data) ? Arr::get($data, 0) : $data;
$operator = is_array($data) ? Arr::get($data, 1, '=') : '=';
$filters[] = array('id' => $meta, 'value' => $value, 'operator' => $operator);
}
$this->filters[]['metas'] = $filters;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240606
|
Encrypt.encode
|
train
|
public function encode($string)
{
if (empty($string) || empty($this->key)) {
throw new \Exception("Can not encrypt with an empty key or no data");
return false;
}
$publicKey = $this->generateKey($string);
$privateKey = $this->key;
//Get a SHA-1 hashKey
$hashKey = sha1($privateKey . "+" . (string)$publicKey);
$stringArray = str_split($string);
$hashArray = str_split($hashKey);
$cipherNoise = str_split($publicKey, 2);
$counter = 0;
for ($i = 0; $i < sizeof($stringArray); $i++) {
if ($counter > 40)
$counter = 0;
$cryptChar = ord((string)$stringArray[$i]) + ord((string)$hashArray[$counter]);
$cryptChar -= floor($cryptChar / 127) * 127;
$cipherStream[$i] = dechex($cryptChar);
$counter++;
}
//print_R($cipherNoise);
$cipherNoiseSize = count($cipherNoise);
$cipher = implode("|x", $cipherStream);
$cipher .= "|x::|x" . ord((string)$cipherNoiseSize) . "|x";
$cipher .= implode("|x", $cipherNoise);
//echo $cipher;
return $cipher;
}
|
php
|
{
"resource": ""
}
|
q240607
|
Encrypt.generateKey
|
train
|
public static function generateKey($txt, $length = null)
{
date_default_timezone_set('UTC');
$possible = "2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ";
$maxlength = (empty($length) || (int)$length > strlen($possible)) ? strlen($possible) : (int)$length;
$random = "";
$i = 0;
while ($i < ($maxlength / 5)) {
// pick a random character from the possible ones
$char = substr($possible, mt_rand(0, $maxlength - 1), 1);
if (!strstr($random, $char)) {
$random .= $char;
$i++;
}
}
$salt = time() . $random;
$rand = mt_rand();
$key = md5($rand . $txt . $salt);
return $key;
}
|
php
|
{
"resource": ""
}
|
q240608
|
Encrypt.decode
|
train
|
public function decode($encrypted)
{
//$cipher_all = explode("/", $cipher_in);
//$cipher = $cipher_all[0];
$blocks = explode("|x", $encrypted);
$delimiter = array_search("::", $blocks);
$cipherStream = array_slice($blocks, 0, (int)$delimiter);
unset($blocks[(int)$delimiter]);
unset($blocks[(int)$delimiter + 1]);
$publicKeyArray = array_slice($blocks, (int)$delimiter);
$publicKey = implode('', $publicKeyArray);
$privateKey = $this->key;
$hashKey = sha1($privateKey . "+" . (string)$publicKey);
$hashArray = str_split($hashKey);
$counter = 0;
for ($i = 0; $i < sizeof($cipherStream); $i++) {
if ($counter > 40)
$counter = 0;
$cryptChar = hexdec($cipherStream[$i]) - ord((string)$hashArray[$counter]);
$cryptChar -= floor($cryptChar / 127) * 127;
$cipherText[$i] = chr($cryptChar);
$counter++;
}
$plaintext = implode("", $cipherText);
return $plaintext;
}
|
php
|
{
"resource": ""
}
|
q240609
|
Udp.send
|
train
|
public function send(MessageInterface $message, $target)
{
$msg = $message->getMessageString();
if (strpos($target, ':')) {
list($host, $port) = explode(':', $target);
} else {
$host = $target;
$port = self::DEFAULT_UDP_PORT;
}
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($sock === false) {
$errorCode = socket_last_error();
$errorMsg = socket_strerror($errorCode);
throw new \RuntimeException("Error creating socket: [$errorCode] $errorMsg");
}
socket_sendto($sock, $msg, strlen($msg), 0, $host, $port);
socket_close($sock);
}
|
php
|
{
"resource": ""
}
|
q240610
|
OptimizeJsTask.getMainJsFileName
|
train
|
private static function getMainJsFileName(string $realPath): string
{
$parts = pathinfo($realPath);
return $parts['dirname'].'/'.$parts['filename'].'.main.'.$parts['extension'];
}
|
php
|
{
"resource": ""
}
|
q240611
|
OptimizeJsTask.minimizeResource
|
train
|
protected function minimizeResource(string $resource, ?string $fullPathName): string
{
list($std_out, $std_err) = $this->runProcess($this->minifyCommand, $resource);
if ($std_err) $this->logInfo($std_err);
return $std_out;
}
|
php
|
{
"resource": ""
}
|
q240612
|
OptimizeJsTask.combine
|
train
|
private function combine(string $realPath): array
{
$config = $this->extractConfigFromMainFile(self::getMainJsFileName($realPath));
// Create temporary file with config.
$tmp_name1 = tempnam('.', 'abc_');
$handle = fopen($tmp_name1, 'w');
fwrite($handle, $config);
fclose($handle);
// Create temporary file for combined JavaScript code.
$tmp_name2 = tempnam($this->resourceDirFullPath, 'abc_');
// Run r.js.
$command = [$this->combineCommand,
'-o',
$tmp_name1,
'baseUrl='.$this->resourceDirFullPath,
'optimize=none',
'name='.$this->getNamespaceFromResourceFilename($realPath),
'out='.$tmp_name2];
$output = $this->execCommand($command);
// Get all files of the combined code.
$parts = [];
$trigger = array_search('----------------', $output);
foreach ($output as $index => $file)
{
if ($index>$trigger && !empty($file))
{
$parts[] = $file;
}
}
// Get the combined the JavaScript code.
$code = file_get_contents($tmp_name2);
if ($code===false) $this->logError("Unable to read file '%s'.", $tmp_name2);
// Get require.js
$path = $this->parentResourceDirFullPath.'/'.$this->requireJsPath;
$require_js = file_get_contents($path);
if ($code===false) $this->logError("Unable to read file '%s'.", $path);
// Combine require.js and all required includes.
$code = $require_js.$code;
// Remove temporary files.
unlink($tmp_name2);
unlink($tmp_name1);
return ['code' => $code, 'parts' => $parts];
}
|
php
|
{
"resource": ""
}
|
q240613
|
OptimizeJsTask.execCommand
|
train
|
private function execCommand(array $command): array
{
$this->logVerbose('Execute: %s', implode(' ', $command));
list($output, $ret) = ProgramExecution::exec1($command, null);
if ($ret!=0)
{
foreach ($output as $line)
{
$this->logInfo($line);
}
$this->logError("Error executing '%s'.", implode(' ', $command));
}
else
{
foreach ($output as $line)
{
$this->logVerbose($line);
}
}
return $output;
}
|
php
|
{
"resource": ""
}
|
q240614
|
OptimizeJsTask.extractPaths
|
train
|
private function extractPaths(string $mainJsFile): array
{
$command = [$this->nodePath,
__DIR__.'/../../lib/extract_config.js',
$mainJsFile];
$output = $this->execCommand($command);
$config = json_decode(implode(PHP_EOL, $output), true);
return [$config['baseUrl'], $config['paths']];
}
|
php
|
{
"resource": ""
}
|
q240615
|
OptimizeJsTask.getFullPathFromClassName
|
train
|
private function getFullPathFromClassName(string $className): string
{
$file_name = str_replace('\\', '/', $className).$this->extension;
$full_path = $this->resourceDirFullPath.'/'.$file_name;
return $full_path;
}
|
php
|
{
"resource": ""
}
|
q240616
|
OptimizeJsTask.getFullPathFromNamespace
|
train
|
private function getFullPathFromNamespace(string $namespace): string
{
$file_name = $namespace.$this->extension;
$full_path = $this->resourceDirFullPath.'/'.$file_name;
return $full_path;
}
|
php
|
{
"resource": ""
}
|
q240617
|
OptimizeJsTask.getMainWithHashedPaths
|
train
|
private function getMainWithHashedPaths(string $realPath): string
{
$main_js_file = self::getMainJsFileName($realPath);
// Read the main file.
$js = file_get_contents($main_js_file);
if ($js===false) $this->logError("Unable to read file '%s'.", $realPath);
// Extract paths from main.
preg_match('/^(.*paths:[^{]*)({[^}]*})(.*)$/sm', $js, $matches);
if (!isset($matches[2])) $this->logError("Unable to find paths in '%s'.", $realPath);
// @todo Remove from paths files already combined.
// Lookup table as paths in requirejs.config, however, keys and values are flipped.
$paths = [];
// Replace aliases to paths with aliases to paths with hashes (i.e. paths to minimized files).
list($base_url, $aliases) = $this->extractPaths($main_js_file);
if (isset($base_url) && isset($paths))
{
foreach ($aliases as $alias => $path)
{
$path_with_hash = $this->getPathInResourcesWithHash($base_url, $path);
if (isset($path_with_hash))
{
$paths[$this->removeJsExtension($path_with_hash)] = $alias;
}
}
}
// Add paths from modules that conform to ADM naming convention to paths with hashes (i.e. path to minimized files).
foreach ($this->getResourcesInfo() as $info)
{
// @todo Skip *.main.js files.
// Test JS file is not already in paths, e.g. 'jquery': 'jquery/jquery'.
if (!isset($paths[$this->removeJsExtension($info['path_name_in_sources_with_hash'])]))
{
if (isset($info['path_name_in_sources']))
{
$module = $this->getNamespaceFromResourceFilename($info['full_path_name']);
$path_with_hash = $this->getNamespaceFromResourceFilename($info['full_path_name_with_hash']);
$paths[$path_with_hash] = $module;
}
}
}
// Convert the paths to proper JS code.
$matches[2] = json_encode(array_flip($paths), JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
array_shift($matches);
$js = implode('', $matches);
return $js;
}
|
php
|
{
"resource": ""
}
|
q240618
|
OptimizeJsTask.getNamespaceFromResourceFilename
|
train
|
private function getNamespaceFromResourceFilename(string $resourceFilename): string
{
$name = $this->getPathInResources($resourceFilename);
// Remove resource dir from name.
$len = strlen(trim($this->resourceDir, '/'));
if ($len>0)
{
$name = substr($name, $len + 2);
}
// Remove extension.
$parts = pathinfo($name);
$name = substr($name, 0, -(strlen($parts['extension']) + 1));
return $name;
}
|
php
|
{
"resource": ""
}
|
q240619
|
Form.FetchFields
|
train
|
private function FetchFields($parent)
{
$child= $this->tree->FirstChildOf($parent);
while ($child)
{
$this->HandleField($child);
$this->FetchFields($child);
$child = $this->tree->NextOf($child);
}
}
|
php
|
{
"resource": ""
}
|
q240620
|
Form.SaveToTable
|
train
|
private function SaveToTable($table)
{
$sql = Access::SqlBuilder();
$fields = array();
$setList = null;
foreach ($this->Elements()->GetElements() as $element)
{
$this->HandleElement($table, $element, $fields, $setList);
}
if ($setList)
{
Access::Connection()->ExecuteQuery($sql->Insert($sql->Table($table, $fields), $setList));
}
}
|
php
|
{
"resource": ""
}
|
q240621
|
FormHelper.prepareSentryPermissionInput
|
train
|
public function prepareSentryPermissionInput(array &$input, $operation, $field_name = "permissions") {
$input[$field_name] = isset($input[$field_name]) ? [$input[$field_name] => $operation] : '';
}
|
php
|
{
"resource": ""
}
|
q240622
|
Bitflag.jsonSerialize
|
train
|
public function jsonSerialize()
{
$ret = new StdClass;
foreach ($this->map as $key => $value) {
$ret->$key = (bool)($this->source & $value);
}
return $ret;
}
|
php
|
{
"resource": ""
}
|
q240623
|
Zend_Loader_StandardAutoloader.autoload
|
train
|
public function autoload($class)
{
$isFallback = $this->isFallbackAutoloader();
if (false !== strpos($class, self::NS_SEPARATOR)) {
if ($this->loadClass($class, self::LOAD_NS)) {
return $class;
} elseif ($isFallback) {
return $this->loadClass($class, self::ACT_AS_FALLBACK);
}
return false;
}
if (false !== strpos($class, self::PREFIX_SEPARATOR)) {
if ($this->loadClass($class, self::LOAD_PREFIX)) {
return $class;
} elseif ($isFallback) {
return $this->loadClass($class, self::ACT_AS_FALLBACK);
}
return false;
}
if ($isFallback) {
return $this->loadClass($class, self::ACT_AS_FALLBACK);
}
return false;
}
|
php
|
{
"resource": ""
}
|
q240624
|
Zend_Loader_StandardAutoloader.transformClassNameToFilename
|
train
|
protected function transformClassNameToFilename($class, $directory)
{
// $class may contain a namespace portion, in which case we need
// to preserve any underscores in that portion.
$matches = array();
preg_match('/(?P<namespace>.+\\\)?(?P<class>[^\\\]+$)/', $class, $matches);
$class = (isset($matches['class'])) ? $matches['class'] : '';
$namespace = (isset($matches['namespace'])) ? $matches['namespace'] : '';
return $directory
. str_replace(self::NS_SEPARATOR, '/', $namespace)
. str_replace(self::PREFIX_SEPARATOR, '/', $class)
. '.php';
}
|
php
|
{
"resource": ""
}
|
q240625
|
Zend_Loader_StandardAutoloader.normalizeDirectory
|
train
|
protected function normalizeDirectory($directory)
{
$last = $directory[strlen($directory) - 1];
if (in_array($last, array('/', '\\'))) {
$directory[strlen($directory) - 1] = DIRECTORY_SEPARATOR;
return $directory;
}
$directory .= DIRECTORY_SEPARATOR;
return $directory;
}
|
php
|
{
"resource": ""
}
|
q240626
|
ConfigBuilder.addResource
|
train
|
public function addResource($resource, $prefix = null)
{
$this->resources[] = [$resource, $prefix, true];
return $this;
}
|
php
|
{
"resource": ""
}
|
q240627
|
ConfigBuilder.addOptionalResource
|
train
|
public function addOptionalResource($resource, $prefix = null)
{
$this->resources[] = [$resource, $prefix, false];
return $this;
}
|
php
|
{
"resource": ""
}
|
q240628
|
ConfigBuilder.loadResource
|
train
|
protected function loadResource($resource, $required)
{
foreach ($this->loaders as $loader) {
if (!$loader->supports($resource)) {
continue;
}
try {
return $loader->load($resource);
} catch (ResourceNotFoundException $e) {
if ($required) {
throw $e;
}
return [];
}
}
throw new ResourceException(sprintf('There is no configuration loader available to load the resource "%s"', $resource));
}
|
php
|
{
"resource": ""
}
|
q240629
|
ConfigBuilder.getConfig
|
train
|
public function getConfig(Schema $schema = null)
{
if (!$schema) {
$schema = new Schema();
}
$config = new Config();
foreach ($this->resources as $resource) {
$values = $this->loadResource($resource[0], $resource[2]);
if (is_string($prefix = $resource[1])) {
$values = [
$prefix => $values,
];
}
$config->merge($values);
}
foreach ($this->processors as $processor) {
$processor->onPostMerge($config, $schema);
}
return $config;
}
|
php
|
{
"resource": ""
}
|
q240630
|
View.templateFile
|
train
|
private function templateFile($name)
{
$filename = $this->viewPath . '/' . str_replace('.', DIRECTORY_SEPARATOR, $name) . '.blade.php';
if (file_exists($filename)) {
return $filename;
}
if (self::$manifest === null) {
if (file_exists($this->pluginManifestOfViews)) {
/** @noinspection PhpIncludeInspection */
self::$manifest = include $this->pluginManifestOfViews;
}
}
return isset(self::$manifest[$name]) ? base_path(self::$manifest[$name]) : null;
}
|
php
|
{
"resource": ""
}
|
q240631
|
View.isCacheUpToDate
|
train
|
private function isCacheUpToDate($cachedFile, $templateFile)
{
if (!file_exists($cachedFile)) {
return false;
}
$cacheTime = filemtime($cachedFile);
$templTime = filemtime($templateFile);
return $cacheTime == $templTime;
}
|
php
|
{
"resource": ""
}
|
q240632
|
View.saveFile
|
train
|
private function saveFile($file, $content, $time)
{
// create directory if not exists
if (!is_dir($dir = dirname($file))) {
// @codeCoverageIgnoreStart
if (!make_dir($dir, 0775)) {
throw new RuntimeException(sprintf('View Template Engine was not able to create directory "%s"', $dir)); // @codeCoverageIgnore
}
// @codeCoverageIgnoreEnd
} // @codeCoverageIgnore
// save file
if (file_exists($file)) {
unlink($file); // so we will to be the owner at the new file
}
if (file_put_contents($file, $content, LOCK_EX) === false) {
throw new RuntimeException(sprintf('View Template Engine was not able to save file "%s"', $file)); // @codeCoverageIgnore
}
@chmod($file, 0664);
// set file modification time
if (!@touch($file, $time)) {
throw new RuntimeException(sprintf('View Template Engine was not able to modify time of file "%s"', $file)); // @codeCoverageIgnore
}
}
|
php
|
{
"resource": ""
}
|
q240633
|
View.storeSection
|
train
|
private function storeSection($section, $content)
{
if (!isset($this->scope->sections[$section])) {
$this->scope->sections[$section] = $content;
}
}
|
php
|
{
"resource": ""
}
|
q240634
|
FileAccessException.Read
|
train
|
public static function Read(
string $file, string $message = null, int $code = \E_USER_ERROR, \Throwable $previous = null )
: FileAccessException
{
return new FileAccessException (
$file,
FileAccessException::ACCESS_READ,
$message,
$code,
$previous
);
}
|
php
|
{
"resource": ""
}
|
q240635
|
FileAccessException.Write
|
train
|
public static function Write(
string $file, string $message = null, int $code = \E_USER_ERROR, \Throwable $previous = null )
: FileAccessException
{
return new FileAccessException (
$file,
FileAccessException::ACCESS_WRITE,
$message,
$code,
$previous
);
}
|
php
|
{
"resource": ""
}
|
q240636
|
MbAsset.runAssets
|
train
|
public function runAssets($pageSlug, $isShortcode = false)
{
$cssList = $this->css;
$jsList = $this->js;
MbWPActionHook::addActionCallback($this->getActionEnqueue(), function () use ($pageSlug, $cssList, $jsList) {
foreach ($cssList as $i => $css) {
wp_enqueue_style("style_mb_{$pageSlug}_{$i}", $css);
}
foreach ($jsList as $i => $js) {
wp_enqueue_script("script_mb_{$pageSlug}_{$i}", $js['path'], [], $js['version'], $js['footer']);
}
});
if ($isShortcode) {
MbWPActionHook::doAction($this->getActionEnqueue());
}
}
|
php
|
{
"resource": ""
}
|
q240637
|
MbAsset.autoEnqueue
|
train
|
protected function autoEnqueue()
{
$request = MocaBonita::getInstance()->getMbRequest();
if ($request->isLoginPage()) {
$this->actionEnqueue = "login_enqueue_scripts";
} elseif ($request->isAdmin()) {
$this->actionEnqueue = "admin_enqueue_scripts";
} else {
$this->actionEnqueue = "wp_enqueue_scripts";
}
}
|
php
|
{
"resource": ""
}
|
q240638
|
MbAsset.setActionEnqueue
|
train
|
public function setActionEnqueue($typePage)
{
switch ($typePage) {
case 'admin' :
$this->actionEnqueue = "admin_enqueue_scripts";
break;
case 'login' :
$this->actionEnqueue = "login_enqueue_scripts";
break;
default :
$this->actionEnqueue = "wp_enqueue_scripts";
break;
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q240639
|
ConnectionFactory.create
|
train
|
public function create($type, $host, $port, $database, $user, $password)
{
return new PDO(
sprintf(
'%s:host=%s;port=%s;dbname=%s',
$type,
$host,
$port,
$database
),
$user,
$password
);
}
|
php
|
{
"resource": ""
}
|
q240640
|
AbstractRequest.addHeaders
|
train
|
public function addHeaders(array $headers)
{
foreach ($headers as $key => $value) {
$header = NULL;
//Handle Array of String based Headers
if (is_numeric($key) && strpos($value,":") !== FALSE) {
$arr = explode(":",$value,2);
if (count($arr)==2){
$header = $arr[0];
$value = trim($arr[1]);
}
} else {
$header = $key;
}
if ($header !== NULL){
$this->addHeader($header, $value);
}
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q240641
|
AbstractRequest.compileOptions
|
train
|
private function compileOptions(){
$this->CurlOptions = array();
$this->configureHTTPMethod($this->method);
$this->configureUrl($this->url);
$this->configureBody($this->body);
$this->configureHeaders($this->headers);
$this->configureOptions($this->options);
return $this;
}
|
php
|
{
"resource": ""
}
|
q240642
|
AbstractRequest.configureHTTPMethod
|
train
|
protected function configureHTTPMethod($method)
{
switch ($method) {
case self::HTTP_GET:
break;
case self::HTTP_POST:
return $this->addCurlOption(CURLOPT_POST, TRUE);
default:
return $this->addCurlOption(CURLOPT_CUSTOMREQUEST, $method);
}
return TRUE;
}
|
php
|
{
"resource": ""
}
|
q240643
|
AbstractRequest.configureHeaders
|
train
|
protected function configureHeaders(array $headers){
$configuredHeaders = array();
foreach($headers as $header => $value){
$configuredHeaders[] = "$header: $value";
}
return $this->addCurlOption(CURLOPT_HTTPHEADER, $configuredHeaders);
}
|
php
|
{
"resource": ""
}
|
q240644
|
AbstractRequest.configureBody
|
train
|
protected function configureBody($body){
$upload = $this->getUpload();
switch ($this->method) {
case self::HTTP_GET:
if (!$upload){
if (is_array($body) || is_object($body)){
$queryParams = http_build_query($body);
} else {
$queryParams = $body;
}
if (!empty($body)){
if (strpos($this->url, "?") === false) {
$queryParams = "?".$queryParams;
} else {
$queryParams = "&".$queryParams;
}
return $this->configureUrl($this->url.$queryParams);
}
break;
}
default:
if ($upload){
$this->addHeader('Content-Type','multipart/form-data');
}
return $this->addCurlOption(CURLOPT_POSTFIELDS, $body);
}
}
|
php
|
{
"resource": ""
}
|
q240645
|
AbstractRequest.init
|
train
|
protected function init()
{
$this->setMethod(static::$_DEFAULT_HTTP_METHOD);
$this->setHeaders(static::$_DEFAULT_HEADERS);
$this->setOptions(static::$_DEFAULT_OPTIONS);
$this->body = NULL;
$this->error = NULL;
$this->status = self::STATUS_INIT;
if (self::$_AUTO_INIT){
return $this->initCurl();
}
return TRUE;
}
|
php
|
{
"resource": ""
}
|
q240646
|
AbstractRequest.configureCurl
|
train
|
private function configureCurl()
{
foreach($this->getCurlOptions() as $option => $value){
curl_setopt($this->CurlRequest,$option,$value);
}
return TRUE;
}
|
php
|
{
"resource": ""
}
|
q240647
|
AbstractRequest.executeCurl
|
train
|
private function executeCurl()
{
if ($this->initCurl()){
$this->configureCurl();
$this->CurlResponse = curl_exec($this->CurlRequest);
$this->checkForError();
return TRUE;
}
return FALSE;
}
|
php
|
{
"resource": ""
}
|
q240648
|
AbstractRequest.checkForError
|
train
|
private function checkForError(){
$curlErrNo = curl_errno($this->CurlRequest);
if ($curlErrNo !== CURLE_OK) {
$this->error = TRUE;
$this->CurlError = array(
'error' => $curlErrNo,
'error_message' => curl_error($this->CurlRequest)
);
}
}
|
php
|
{
"resource": ""
}
|
q240649
|
GitIgnoreFile.setFile
|
train
|
public function setFile($filePath = '.gitignore')
{
$this->fileContent = array();
$this->afterLine = null;
$this->filePath = $filePath;
$this->checkPermissions();
$this->parse();
}
|
php
|
{
"resource": ""
}
|
q240650
|
GitIgnoreFile.setLines
|
train
|
public function setLines($lines)
{
if (!is_array($lines)) {
$this->lines = array(
$lines
);
} else {
$this->lines = $lines;
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q240651
|
FileUtils.isAbsolute
|
train
|
public static function isAbsolute($path)
{
return ((isset($path[0])
? ($path[0] == '/'
|| (ctype_alpha($path[0]) && ($path[1] == ':')))
: '')
|| (parse_url($path, PHP_URL_SCHEME) === true))
? true
: false;
}
|
php
|
{
"resource": ""
}
|
q240652
|
FileUtils.getMime
|
train
|
public static function getMime($file)
{
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($fileInfo, $file);
return empty($mime) ? : $mime;
}
|
php
|
{
"resource": ""
}
|
q240653
|
TextSprite.render
|
train
|
public function render(): Image {
$ftbbox = imageftbbox($this->fontSize, 0, $this->fontFile, $this->text, $this->extraInfo);
$width = max($ftbbox[2] - $ftbbox[6], 1);
$height = max($ftbbox[3] - $ftbbox[7], 1);
// Getting an offset for the first symbol of text
$ftbbox = imageftbbox($this->fontSize, 0, $this->fontFile, $this->text[0] ?? '', $this->extraInfo);
$offset = $ftbbox[3] - $ftbbox[7];
$image = Utility::transparentImage($width, $height);
imagefttext(
$image->getResource(),
$this->fontSize,
0,
0,
$offset,
$this->color->allocate($image->getResource()),
$this->fontFile,
$this->text,
$this->extraInfo
);
return $image;
}
|
php
|
{
"resource": ""
}
|
q240654
|
TokenBlacklistRepositoryEloquent.check
|
train
|
public function check($token)
{
$blacklistedToken = $this->model
->where('user_id', $this->Token->getSubject($token))
->where('expiry', '>', Carbon::now())
->whereToken($token)
->first();
if ($blacklistedToken === null) {
return true;
}
throw new BlacklistedTokenException();
}
|
php
|
{
"resource": ""
}
|
q240655
|
TokenBlacklistRepositoryEloquent.findByToken
|
train
|
public function findByToken($token)
{
$blacklistedToken = $this->model->whereToken($token)->first();
if ($blacklistedToken === null)
{
throw new ModelNotFoundException();
}
return $blacklistedToken->toArray();
}
|
php
|
{
"resource": ""
}
|
q240656
|
TokenBlacklistRepositoryEloquent.findAllExpired
|
train
|
public function findAllExpired()
{
$expiredBlacklistedTokens = $this->model->where('expiry', '<', Carbon::now())->get();
return $expiredBlacklistedTokens->toArray();
}
|
php
|
{
"resource": ""
}
|
q240657
|
TokenBlacklistRepositoryEloquent.deleteAllExpired
|
train
|
public function deleteAllExpired()
{
$expiredBlacklistedTokens = $this->findAllExpired();
foreach ($expiredBlacklistedTokens as $expiredBlacklistedToken)
{
$this->delete($expiredBlacklistedToken['id']);
}
}
|
php
|
{
"resource": ""
}
|
q240658
|
QueryObject.updateCollection
|
train
|
public function updateCollection(EntityChangeEventInterface $event)
{
$collection = $event->getCollection();
if ($collection->getId()) {
$collectionMap = $this->getCollectionsMap();
$collectionMap
->set($collection->getId(), $collection);
}
}
|
php
|
{
"resource": ""
}
|
q240659
|
QueryObject.query
|
train
|
protected function query(Select $sql)
{
$cid = $this->getId($sql);
$collection = $this->repository
->getCollectionsMap()
->get($cid, false);
if (false === $collection) {
$collection = $this->getCollection($sql, $cid);
}
return $collection;
}
|
php
|
{
"resource": ""
}
|
q240660
|
QueryObject.getCollection
|
train
|
protected function getCollection(Select $sql, $cid)
{
$this->triggerBeforeSelect(
$sql,
$this->getRepository()->getEntityDescriptor()
);
$data = $this->adapter->query($sql, $sql->getParameters());
$collection = $this->repository->getEntityMapper()
->createFrom($data);
$this->triggerAfterSelect(
$data,
$collection
);
$this->registerEventsTo($collection, $cid);
$this->getCollectionsMap()->set($cid, $collection);
$this->updateIdentityMap($collection);
return $collection;
}
|
php
|
{
"resource": ""
}
|
q240661
|
QueryObject.getCollectionsMap
|
train
|
protected function getCollectionsMap()
{
if (null == $this->collectionsMap) {
$this->collectionsMap = $this->repository->getCollectionsMap();
}
return $this->collectionsMap;
}
|
php
|
{
"resource": ""
}
|
q240662
|
QueryObject.registerEventsTo
|
train
|
protected function registerEventsTo(EntityCollection $collection, $cid)
{
$collection->setId($cid);
$collection->getEmitter()
->addListener(
EntityAdded::ACTION_ADD,
[$this, 'updateCollection']
);
$collection->getEmitter()
->addListener(
EntityRemoved::ACTION_REMOVE,
[$this, 'updateCollection']
);
$entity = $this->repository->getEntityDescriptor()->className();
Orm::addListener(
$entity,
Delete::ACTION_AFTER_DELETE,
function (Delete $event) use ($collection) {
$collection->remove($event->getEntity());
},
EmitterInterface::P_HIGH
);
return $this;
}
|
php
|
{
"resource": ""
}
|
q240663
|
QueryObject.getId
|
train
|
protected function getId(Select $query)
{
$str = $query->getQueryString();
$search = array_keys($query->getParameters());
$values = array_values($query->getParameters());
return str_replace($search, $values, $str);
}
|
php
|
{
"resource": ""
}
|
q240664
|
QueryObject.updateIdentityMap
|
train
|
protected function updateIdentityMap(EntityCollection $collection)
{
if ($collection->isEmpty()) {
return $this;
}
foreach ($collection as $entity)
{
$this->repository->getIdentityMap()->set($entity);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q240665
|
SourceRoad.resourcePathMatch
|
train
|
protected function resourcePathMatch(File $file) {
$source_dirpath = str_replace('#', '\#', $this->sourceDir->getAbsolutePath());
$source_dirpath = str_replace('[', '\[', $source_dirpath);
$source_dirpath = str_replace(']', '\]', $source_dirpath);
$source_dirpath = str_replace('(', '\(', $source_dirpath);
$source_dirpath = str_replace(')', '\)', $source_dirpath);
return preg_match('#^' . $source_dirpath . '/' . $this->getRegex() . '#', $file->getAbsolutePath()) ? TRUE : FALSE;
}
|
php
|
{
"resource": ""
}
|
q240666
|
SourceRoad.releaseResource
|
train
|
public function releaseResource(AbstractResourceFile $resource) {
if (is_null($this->getReleaseDir())) {
throw new Exception("ERROR: RELEASE DIR IS NULL: " . $resource->getRealPath());
}
if (!$this->getReleaseDir()->exists()) {
$this->getReleaseDir()->mkdirs();
}
$release_file = $this->makeReleaseFile($resource);
$release_dir = $release_file->getAbsoluteFile()->getParentFile();
if (!$release_dir->exists()) {
if (!$release_dir->mkdirs()) {
throw new FileWriteErrorException("The directory '" . $release_dir->getAbsolutePath() . "' create fails.");
}
}
\file_put_contents($release_file->getAbsolutePath(), $resource->getFileContents());
}
|
php
|
{
"resource": ""
}
|
q240667
|
SourceRoad.makeReleaseFile
|
train
|
public final function makeReleaseFile(AbstractResourceFile $resource) {
if (!isset($this->__release__file__map[$resource->getMemberId()])) {
$this->__release__file__map[$resource->getMemberId()] = new File($this->makeReleaseRelativePath($resource), $this->getReleaseDir()->getAbsolutePath());
}
return $this->__release__file__map[$resource->getMemberId()];
}
|
php
|
{
"resource": ""
}
|
q240668
|
SourceRoad.getParentProject
|
train
|
public final function getParentProject() {
if (\is_null($this->__parent__project)) {
$result = ProjectUtil::searchRelativeProject($this);
if (\count($result) < 1) {
throw new ProjectMemberNotFoundException("SOURCE ROAD NOT FOUND");
}
$this->__parent__project = $result[0];
}
return $this->__parent__project;
}
|
php
|
{
"resource": ""
}
|
q240669
|
Field.setCondition
|
train
|
public function setCondition($field_name, $value, $operation = '=')
{
$this->condition[$field_name] = [
'value' => $value,
'operation' => $operation
];
return $this;
}
|
php
|
{
"resource": ""
}
|
q240670
|
Field.asQuestion
|
train
|
public function asQuestion()
{
$instance = $this->questionClassInstance()
->setMaxAttempts($this->maxAttempt);
// Set question instance hidden if defined by the field.
if ($this->hidden) {
$instance->setHidden(true);
}
// Set validation callback if field is required.
if ($this->isRequire()) {
$this->setValidation(function ($answer) {
if ($answer == ''
&& $this->dataType() !== 'boolean') {
throw new \Exception('Field is required.');
}
});
}
// Set question instance validator callback.
$instance->setValidator(function ($answer) {
// Iterate over all field validation callbacks.
foreach ($this->validation as $callback) {
if (!is_callable($callback)) {
continue;
}
$callback($answer);
}
return $answer;
});
// Set question normalizer based on the field normalizer. If a default
// normalizer is being set from the question class then setting the
// normalizer will trump it's execution, as only one normalizer can be
// set per question instance.
if (isset($this->normalizer)
&& is_callable($this->normalizer)) {
$instance->setNormalizer($this->normalizer);
}
return $instance;
}
|
php
|
{
"resource": ""
}
|
q240671
|
Field.questionClassInstance
|
train
|
protected function questionClassInstance()
{
$classname = $this->questionClass();
if (!class_exists($classname)) {
throw new \Exception('Invalid question class.');
}
$instance = (new \ReflectionClass($classname))
->newInstanceArgs($this->questionClassArgs());
if (!$instance instanceof \Symfony\Component\Console\Question\Question) {
throw new \Exception('Invalid question class instance');
}
return $instance;
}
|
php
|
{
"resource": ""
}
|
q240672
|
Container.singleton
|
train
|
public function singleton($alias, $callback, $share = false)
{
return $this->add($alias, $callback, $share)->setSingleton(true);
}
|
php
|
{
"resource": ""
}
|
q240673
|
Container.resolve
|
train
|
public function resolve($alias, array $args = [])
{
// if it is an alias we will solve the orjinal one
if (isset($this->aliases[$alias])) {
$alias = $this->aliases[$alias];
}
$singleton = $this->getBoundManager()->singleton($alias);
// determine the alias already resolved before or not.
if ($singleton && $this->hasResolvedBefore($alias)) {
// we resolved that before, let's reuse it.
return $this->getAlreadyResolved($alias);
}
// we realized we did not add this before
if (false === $this->boundManager->has($alias)) {
$this->add($alias, $alias);
// resolve this service with given args
return $this->resolve($alias, $args);
}
$definition = $this
->boundManager
->findDefinition($alias);
// if we add new args, we'll set them into definition
if ( ! empty($args)) {
$this->getArgumentManager()->setClassArgs(
$alias,
$args
);
}
// determine resolved instance is as we expected or not
$resolved = $this->checkExpectation(
$alias,
$this->resolveObject($definition, $alias)
);
// we resolved the definition, now we will add into resolvedBond or sharedResolved
// and we will reuse they when we want to resolve them
$this->saveResolved($alias, $resolved);
// we already resolve and saved it. We don't need this definition anymore.
// so we will remove it.
// this will save memory
if ($singleton === true) {
$this->removeResolvedFromBound($alias);
}
return $resolved;
}
|
php
|
{
"resource": ""
}
|
q240674
|
Container.resolveObject
|
train
|
private function resolveObject($definition, $alias)
{
if ($definition instanceof \Closure) {
return $this->resolveClosure(
$alias,
$definition
);
}
try {
$class = new \ReflectionClass($definition);
} catch (\ReflectionException $exception) {
throw new ReflectionException(
$exception->getMessage()
);
}
$this->resolveProviderAnnotations($class);
// the given class if is not instantiable throw an exception
// that happens when you try resolve an interface or abstract class
// without saving an alias on that class before
if (false === $class->isInstantiable()) {
throw new ReflectionException(
sprintf(
'%s class in not instantiable, probably an interface or abstract',
$class->getName()
)
);
}
$constructor = $class->getConstructor();
$parameters = [];
if (null !== $constructor) {
$this->resolveInjectAnnotations($constructor, $alias);
$parameters = $this->resolveParameters(
$constructor,
$this->argumentManager->getClassArgs($alias)
);
}
return $class->newInstanceArgs($parameters);
}
|
php
|
{
"resource": ""
}
|
q240675
|
PHPArray.each
|
train
|
public static function each(array $arr, \Closure $action){
foreach($arr as $k => $v){
$action($v, $k);
}
}
|
php
|
{
"resource": ""
}
|
q240676
|
PHPArray.filter
|
train
|
public static function filter(array $arr, \Closure $predicate){
$ret = array();
foreach($arr as $k => $v){
if($predicate($v, $k)){
$ret[$k] = $v;
}
}
return $ret;
}
|
php
|
{
"resource": ""
}
|
q240677
|
PHPArray.findKey
|
train
|
public static function findKey(array $arr, \Closure $predicate){
foreach($arr as $k => $v){
if($predicate($v, $k)){
return $k;
}
}
return null;
}
|
php
|
{
"resource": ""
}
|
q240678
|
PHPArray.keysExist
|
train
|
public static function keysExist(array $arr /*, $key1, $key2, etc...*/){
for($i = 1, $l = \func_num_args() - 1; $i <= $l; ++$i){
if(!\array_key_exists(\func_get_arg($i), $arr)){
return false;
}
}
return true;
}
|
php
|
{
"resource": ""
}
|
q240679
|
PHPArray.map
|
train
|
public static function map(array $arr, \Closure $callback){
$ret = array();
foreach($arr as $k => $v){
$ret[$k] = $callback($v, $k);
}
return $ret;
}
|
php
|
{
"resource": ""
}
|
q240680
|
PHPArray.single
|
train
|
public static function single(array $arr, \Closure $predicate){
foreach($arr as $k => $v){
if($predicate($v, $k)){
return $v;
}
}
return null;
}
|
php
|
{
"resource": ""
}
|
q240681
|
PHPArray.some
|
train
|
public static function some(array $arr, \Closure $predicate){
foreach($arr as $k => $v){
if($predicate($v, $k)){
return true;
}
}
return false;
}
|
php
|
{
"resource": ""
}
|
q240682
|
PackageInformation.getPackageInfo
|
train
|
public function getPackageInfo($packageName)
{
$composerLock = json_decode($this->finder->get('composer.lock'));
foreach ($composerLock->packages as $package) {
if ($package->name == $packageName) {
return $package;
}
}
}
|
php
|
{
"resource": ""
}
|
q240683
|
Addressable.getAddressInfo
|
train
|
public function getAddressInfo()
{
$address = new Address();
$address->setAddress($this->getAddress());
$address->setPostalCode($this->getPostalCode());
$address->setCity($this->getCity());
if(!is_null($this->getState()))$address->setState($this->getState());
$address->setCountry($this->getCountry());
return $address;
}
|
php
|
{
"resource": ""
}
|
q240684
|
HttpClient.send
|
train
|
public function send(RequestInterface $request)
{
/** @var RequestEvent $event */
$event = new RequestEvent($request);
$event = $this->eventDispatcher->dispatch(ClientEvents::REQUEST, $event);
$request = $event->getRequest();
$response = $this->httpClient->send($request);
/** @var ResponseEvent $event */
$event = new ResponseEvent($response);
$event = $this->eventDispatcher->dispatch(ClientEvents::RESPONSE, $event);
return $event->getResponse();
}
|
php
|
{
"resource": ""
}
|
q240685
|
Model.update
|
train
|
public function update($attributes)
{
try {
self::init();
foreach ($attributes as $column => $value) {
$columns[] = $column. ' = :'.$column;
}
$sql = 'UPDATE ' . self::$modelTable . ' SET ' . implode(', ', $columns) . ' WHERE id = ' . $this->id;
$stm = self::$connect->prepare($sql);
$stm->execute($attributes);
$this->setAttributes($attributes);
return $this;
} catch (\Exception $exception) {
var_dump($exception->getMessage());
}
}
|
php
|
{
"resource": ""
}
|
q240686
|
Model.select
|
train
|
public static function select()
{
try {
self::init();
$columns = func_get_args();
$query = 'SELECT ' . implode(', ', $columns) . ' FROM ' . self::$modelTable;
return new QueryBuilder(self::$connect, $query);
} catch (\Exception $exception) {
var_dump($exception->getMessage());
}
}
|
php
|
{
"resource": ""
}
|
q240687
|
Model.find
|
train
|
public static function find($id)
{
self::init();
$query = 'SELECT * FROM ' . self::$modelTable . ' WHERE id = '.$id;
$qb = new QueryBuilder(self::$connect, $query);
$rows = $qb->get();
$collection = self::makeCollection($rows);
return !empty($collection) ? array_shift($collection) : null;
}
|
php
|
{
"resource": ""
}
|
q240688
|
Model.makeCollection
|
train
|
public static function makeCollection($rows)
{
$collection = [];
foreach ($rows as $row)
{
$obj = new static;
$collection[] = $obj->setAttributes(get_object_vars($row));
}
return $collection;
}
|
php
|
{
"resource": ""
}
|
q240689
|
FileSystem.fgets
|
train
|
public function fgets( $length = null )
{
return $this->validHandle() ? fgets( $this->_fileHandle, $length ) : false;
}
|
php
|
{
"resource": ""
}
|
q240690
|
FileSystem.makePath
|
train
|
public static function makePath( $validate = true, $forceCreate = false )
{
$_arguments = func_get_args();
$_validate = $_path = null;
foreach ( $_arguments as $_part )
{
if ( is_bool( $_part ) )
{
$_validate = $_part;
continue;
}
$_path .= DIRECTORY_SEPARATOR . trim( $_part, DIRECTORY_SEPARATOR . ' ' );
}
if ( !is_dir( $_path = realpath( $_path ) ) )
{
if ( $_validate && !$forceCreate )
{
return false;
}
if ( $forceCreate )
{
if ( false === @mkdir( $_path, 0, true ) )
{
throw new UtilityException( 'The result path "' . $_path . '" could not be created.' );
}
}
}
return $_path;
}
|
php
|
{
"resource": ""
}
|
q240691
|
FileSystem.rmdir
|
train
|
public static function rmdir( $dirPath, $force = false )
{
$_path = rtrim( $dirPath ) . DIRECTORY_SEPARATOR;
if ( !$force )
{
return rmdir( $_path );
}
if ( !is_dir( $_path ) )
{
throw new \InvalidArgumentException( '"' . $_path . '" is not a directory or bogus in some other way.' );
}
$_files = glob( $_path . '*', GLOB_MARK );
foreach ( $_files as $_file )
{
if ( is_dir( $_file ) )
{
static::rmdir( $_file, true );
}
else
{
unlink( $_file );
}
}
return rmdir( $_path );
}
|
php
|
{
"resource": ""
}
|
q240692
|
Joyst_Model.FilterFields
|
train
|
function FilterFields($array, $operation = 'where') {
if (!$array)
return;
$out = array();
foreach ($array as $field => $value) {
if ($operation == 'where' && $this->source == 'internal' && preg_match('/^(.*) (.*)$/', $field, $matches)) { // special CI syntax in key e.g. 'status !=' => 'something' (only for 'where' operations)
$key = $matches[1];
$cond = $matches[2];
$val = $value;
} elseif ($operation == 'where' && $this->source == 'controller' && is_string($value) && preg_match('/^([\<\>]=?)(.*)$/', $value, $matches)) { // CI syntax in value e.g. '>=value'
$key = $field;
$cond = $matches[1];
$val = $matches[2];
} elseif ($operation == 'where' && $this->source == 'controller' && is_array($value) && preg_match('/^([\<\>]=?)(.*)$/', $value[0], $matches)) { // CI syntax in value via array (e.g. ['>=value', '<=value'])
// Accept an array of where conditions - this works around the fact that PHP will always accept the LAST where condition in an URL
// e.g. ?foo=>1&foo=<10 (foo will == '<10')
// Use ?foo[]=>1&foo[]=<10 to work around this
$key = $field;
$cond = $matches[1];
$val = $matches[2];
array_shift($value); // Remove first element - which we've already taken care of
foreach ($value as $valIndex => $valArray) {
if (preg_match('/^([\<\>]=?)(.*)$/', $value[$valIndex], $matches))
$out[isset($matches[1]) && $matches[1] != '=' ? "$key {$matches[1]}" : $key] = $matches[2];
}
} else {
$key = $field;
$cond = '=';
$val = $value;
}
if (!isset($this->schema[$key])) // Field definition does not exist at all
continue;
if ( // Is read-only during a 'set'
$operation == 'set' &&
isset($this->schema[$key]['allowset']) &&
!$this->schema[$key]['allowset']
)
continue;
if ( // Is not filterable by
$operation == 'where' &&
isset($this->schema[$key]['allowquery']) &&
!$this->schema[$key]['allowquery']
)
continue;
// If we got this far its a valid field
$out[$cond && $cond != '=' ? "$key $cond" : $key] = $val;
}
return $out;
}
|
php
|
{
"resource": ""
}
|
q240693
|
Joyst_Model.GetCache
|
train
|
function GetCache($type, $id) {
if (!isset($this->cache[$type]) || !$this->cache[$type]) // Dont cache this type of call
return FALSE;
if (isset($this->_cache[$type][$id]))
return $this->_cache[$type][$id];
return FALSE;
}
|
php
|
{
"resource": ""
}
|
q240694
|
Joyst_Model.SetCache
|
train
|
function SetCache($type, $id, $value) {
if (!isset($this->cache[$type]) || !$this->cache[$type]) // Dont cache this type of call
return $value;
if ($value) {
if (!isset($this->_cache[$type]))
$this->_cache[$type] = array();
$this->_cache[$type][$id] = $value;
return $this->_cache[$type][$id];
} elseif (isset($this->_cache[$type][$id])) {
unset($this->_cache[$type][$id]);
return null;
}
}
|
php
|
{
"resource": ""
}
|
q240695
|
Joyst_Model.ClearCache
|
train
|
function ClearCache($type = null, $id = null) {
if (!$type) { // Clear everything
$this->_cache = array();
} elseif (!$id) { // Clear on section
$this->_cache[$type] = array();
} else { // Clear a specific type/id combination
$this->SetCache($type, $id, null);
}
}
|
php
|
{
"resource": ""
}
|
q240696
|
Joyst_Model.Get
|
train
|
function Get($id) {
$this->continue = TRUE;
$this->LoadSchema();
if ($value = $this->GetCache('get', $id))
return $value;
$this->ResetQuery(array(
'method' => 'get',
'table' => $this->table,
'where' => array(
$this->schema['_id']['field'] => $id,
),
'limit' => 1,
));
$this->db->from($this->query['table']);
$this->db->where("{$this->table}.{$this->schema['_id']['field']}", $id);
$this->db->limit(1);
$row = $this->db->get()->row_array();
if ($row)
$this->ApplyRow($row);
if (!$this->continue)
return FALSE;
$this->Trigger('access', $this->query['where']);
if (!$this->continue)
return FALSE;
$this->Trigger('pull', $this->query['where']);
if (!$this->continue)
return FALSE;
return $this->SetCache('get', $id, $row);
}
|
php
|
{
"resource": ""
}
|
q240697
|
Joyst_Model.GetAll
|
train
|
function GetAll($where = null, $orderby = null, $limit = null, $offset = null) {
$this->LoadSchema();
if ($this->UseCache('getall')) {
$params = func_get_args();
$cacheid = md5(json_encode($params));
if ($value = $this->GetCache('getall', $cacheid))
return $value;
}
$this->ResetQuery(array(
'method' => 'getall',
'table' => $this->table,
'where' => $where,
'orderby' => $orderby,
'limit' => $limit,
'offset' => $offset,
));
$this->Trigger('access', $where);
if (!$this->continue)
return array();
$this->Trigger('pull', $where);
if (!$this->continue)
return array();
$this->Trigger('getall', $where, $orderby, $limit, $offset);
if (!$this->continue)
return array();
$this->db->from($this->table);
if ($where = $this->FilterFields($where, 'where'))
$this->db->where($where);
if ($orderby)
$this->db->order_by($orderby);
if ($limit || $offset)
$this->db->limit($limit,$offset);
$out = array();
foreach ($this->db->get()->result_array() as $row) {
$this->ApplyRow($row);
if (!$this->continue)
return array();
$out[] = $row;
}
$this->Trigger('rows', $out);
if (!$this->continue)
return array();
return isset($cacheid) ? $this->SetCache('getall', $cacheid, $out) : $out;
}
|
php
|
{
"resource": ""
}
|
q240698
|
Joyst_Model.UnCastType
|
train
|
function UnCastType($type, $data, &$row = null) {
switch ($type) {
case 'json':
return json_encode($data);
case 'json-import':
if (!is_array($data))
$data = array();
foreach ($row as $key => $val) {
if (substr($key, 0, 1) == '_') // Skip meta fields
continue;
if (!isset($this->schema[$key])) { // This key is unrecognised - import into JSON blob
$data[$key] = $val;
unset($row[$key]);
}
}
$data = json_encode($data);
return $data;
default: // No idea what this is or we dont care
return $data;
}
}
|
php
|
{
"resource": ""
}
|
q240699
|
Joyst_Model.Create
|
train
|
function Create($data) {
if (!$this->allowBlankCreate && !$data)
return;
$this->LoadSchema();
if ($this->enforceTypes)
foreach ($this->schema as $key => $props)
if (isset($data[$key]) || $props['type'] == 'json-import')
$data[$key] = $this->UnCastType($props['type'], isset($data[$key]) ? $data[$key] : null, $data);
$this->ResetQuery(array(
'method' => 'create',
'table' => $this->table,
'data' => $data,
));
$this->Trigger('access', $data);
if (!$this->continue)
return FALSE;
$this->Trigger('push', $data);
if (!$this->continue)
return FALSE;
$this->Trigger('create', $data);
if (! $data = $this->FilterFields($data, 'set')) // Nothing to save
return FALSE;
if (!$this->continue)
return FALSE;
$this->db->insert($this->table, $data);
$id = $this->db->insert_id();
$this->Trigger('created', $id, $data);
return $this->returnRow ? $this->Get($id) : $id;
}
|
php
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.