_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q240900
|
EmailSerializable.setSender
|
train
|
public function setSender(ContactInterface $sender = null)
{
if ($sender !== null && !($sender instanceof Contact)) {
throw new InvalidArgumentException(
sprintf(
'%s expects an instance of %s.',
__FUNCTION__, Contact::class
)
);
}
$this->sender = $sender;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240901
|
EmailSerializable.setBodyParts
|
train
|
public function setBodyParts(array $bodyParts)
{
$collection = new EmailBodyPartCollection();
foreach ($bodyParts as $k => $v) {
$collection->add($v);
}
$this->bodyParts = $collection;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240902
|
Controller.respondTo
|
train
|
public function respondTo($func)
{
$route = Router::currentRoute();
$response = $func($route['extension'], $this);
if ($response === null) {
return $this->show404();
}
return $response;
}
|
php
|
{
"resource": ""
}
|
q240903
|
Controller.show404
|
train
|
public function show404()
{
$this->executeAction = false;
return new Response(function($resp){
$resp->status = 404;
$resp->body = $this->renderView($this->notFoundView, [
'_layout' => $this->layout
]);
});
}
|
php
|
{
"resource": ""
}
|
q240904
|
Controller.addFilter
|
train
|
protected function addFilter($when, $action, $callback)
{
if (!is_callable($callback) && !is_array($callback)) {
$callback = [$this, $callback];
}
if (is_array($action)) {
foreach ($action as $method) {
$this->addFilter($when, $method, $callback);
}
} else {
EventDispatcher::addListener("{$when}." . get_called_class() . "::{$action}", $callback);
}
}
|
php
|
{
"resource": ""
}
|
q240905
|
Logger.addAdaptor
|
train
|
public function addAdaptor(AbstractAdaptor $adaptor)
{
// The key will be the adaptor's name or the next numerical
// count if a name is blank
$adaptorName = $adaptor->getName() ?: $this->adaptorCount;
$this->adaptors[$adaptorName] = $adaptor;
$this->adaptorCount++;
}
|
php
|
{
"resource": ""
}
|
q240906
|
StockTransferController.showAction
|
train
|
public function showAction(StockTransfer $stocktransfer)
{
$editForm = $this->createForm(new StockTransferType(), $stocktransfer, array(
'action' => $this->generateUrl('stock_transfers_update', array('id' => $stocktransfer->getid())),
'method' => 'PUT',
));
$deleteForm = $this->createDeleteForm($stocktransfer->getId(), 'stock_transfers_delete');
return array(
'stocktransfer' => $stocktransfer,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
|
php
|
{
"resource": ""
}
|
q240907
|
StockTransferController.newAction
|
train
|
public function newAction()
{
$stocktransfer = new StockTransfer();
$nextCode = $this->get('flower.stock.service.stock_transfer')->getNextCode();
$stocktransfer->setCode($nextCode);
$stocktransfer->setUser($this->getUser());
$form = $this->createForm(new StockTransferType(), $stocktransfer);
return array(
'stocktransfer' => $stocktransfer,
'form' => $form->createView(),
);
}
|
php
|
{
"resource": ""
}
|
q240908
|
StockTransferController.createAction
|
train
|
public function createAction(Request $request)
{
$stocktransfer = new StockTransfer();
$stocktransfer->setUser($this->getUser());
$form = $this->createForm(new StockTransferType(), $stocktransfer);
if ($form->handleRequest($request)->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($stocktransfer);
$em->flush();
return $this->redirect($this->generateUrl('stock_transfers_show', array('id' => $stocktransfer->getId())));
}
return array(
'stocktransfer' => $stocktransfer,
'form' => $form->createView(),
);
}
|
php
|
{
"resource": ""
}
|
q240909
|
StockTransferController.updateAction
|
train
|
public function updateAction(StockTransfer $stocktransfer, Request $request)
{
$editForm = $this->createForm(new StockTransferType(), $stocktransfer, array(
'action' => $this->generateUrl('stock_transfers_update', array('id' => $stocktransfer->getid())),
'method' => 'PUT',
));
if ($editForm->handleRequest($request)->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirect($this->generateUrl('stock_transfers_show', array('id' => $stocktransfer->getId())));
}
$deleteForm = $this->createDeleteForm($stocktransfer->getId(), 'stock_transfers_delete');
return array(
'stocktransfer' => $stocktransfer,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
|
php
|
{
"resource": ""
}
|
q240910
|
AdminController.actionChangeStatus
|
train
|
public function actionChangeStatus($id, $value)
{
$model = $this->findModel($id);
if (empty($model)) {
Yii::$app->session->setFlash('error', Yii::t($this->tcModule, 'User {id} not found.', ['id' => $id]));
} else {
$model->status = $value;
$model->pageSize = intval($this->module->params['pageSizeAdmin']);
$result = $model->save(true, ['status']); // update only status field
if ($result) {
Yii::$app->session->setFlash('success', Yii::t($this->tcModule, 'Status changed.'));
} else {
foreach ($model->errors as $attribute => $errors) {
Yii::$app->session->setFlash('error',
Yii::t($this->tcModule, "Status didn't change.")
. ' '
. Yii::t($this->tcModule, "Error on field: '{field}'.", ['field' => $attribute])
. ' ' . $errors[0]
);
break;
}
}
}
return $this->redirect(['index',
'id' => $id,
'page' => empty($model->page) ? 1 : $model->page,
]);
}
|
php
|
{
"resource": ""
}
|
q240911
|
Mapper.getRelation
|
train
|
public function getRelation($relationName) {
$relationInstance = null;
if (isset($this->relations[$relationName])) {
$relationInstance = $this->relations[$relationName];
}
return $relationInstance;
}
|
php
|
{
"resource": ""
}
|
q240912
|
Mapper.getFilter
|
train
|
public function getFilter($filtername) {
$filter = null;
if (!is_null($this->filters) && isset($this->filters[$filtername])) {
$filter = $this->filters[$filtername];
}
return $filter;
}
|
php
|
{
"resource": ""
}
|
q240913
|
AbstractRepository.getEntityNameFromClassName
|
train
|
public static function getEntityNameFromClassName(string $className)
{
$entityName = constant(sprintf(self::ENTITY_NAME_CONST_FORMAT, $className));
if ($entityName === AbstractEntity::ENTITY_NAME or !is_string($entityName)) {
throw new NoEntityNameException($className);
}
return $entityName;
}
|
php
|
{
"resource": ""
}
|
q240914
|
AbstractRepository.loadRegistries
|
train
|
public function loadRegistries()
{
$registries = $this->registryFactory->getDefaultRegistries();
foreach ($registries as $registry) {
$this->addRegistry($registry);
}
}
|
php
|
{
"resource": ""
}
|
q240915
|
AbstractRepository.getEntityName
|
train
|
public function getEntityName()
{
if (is_null($this->entityName)) {
$this->entityName = self::getEntityNameFromClassName($this->getEntityClass());
}
return $this->entityName;
}
|
php
|
{
"resource": ""
}
|
q240916
|
AbstractRepository.findById
|
train
|
public function findById(int $id)
{
$entity = null;
for ($i = 0; $i < count($this->registries); $i++) {
/** @var RegistryInterface $registry */
$registry = $this->registries[ $i ];
$entity = $registry->findByKey($id);
if ($entity instanceof AbstractEntity) {
$this->updateRegistries([$entity], $i - 1);
break;
}
}
return $entity;
}
|
php
|
{
"resource": ""
}
|
q240917
|
AbstractRepository.findByIds
|
train
|
public function findByIds(array $ids)
{
$entities = [];
for ($i = 0; $i < count($this->registries); $i++) {
/** @var RegistryInterface $registry */
$registry = $this->registries[ $i ];
$found = $registry->findByKeys($ids);
$entities = array_merge($entities, $found);
$this->updateRegistries($found, $i - 1);
if (count($entities) === count($ids)) {
break;
}
}
return $entities;
}
|
php
|
{
"resource": ""
}
|
q240918
|
AbstractRepository.findOneBy
|
train
|
public function findOneBy(array $criteria = [], array $orders = [], $offset = null): ?AbstractEntity
{
$array = $this->findBy($criteria, $orders, 1, $offset);
return array_shift($array);
}
|
php
|
{
"resource": ""
}
|
q240919
|
AbstractRepository.matching
|
train
|
public function matching(Criteria $criteria): array
{
$queryBuilder = $this->entityManager->createQueryBuilder()
->select('e.id')
->from($this->getEntityName(), 'e');
$queryBuilder->addCriteria($criteria);
$ids = $queryBuilder->getQuery()->getResult(ColumnHydrator::HYDRATOR_MODE);
if (count($ids) === 0) {
return [];
}
return $this->findByIds($ids);
}
|
php
|
{
"resource": ""
}
|
q240920
|
AbstractRepository.getEntityRepository
|
train
|
public function getEntityRepository()
{
$repository = $this->entityManager->getRepository($this->getEntityName());
if (!($repository instanceof EntityRepository)) {
throw new InvalidEntityNameException($this->getEntityName(), $this->getEntityClass());
}
return $repository;
}
|
php
|
{
"resource": ""
}
|
q240921
|
AbstractRepository.updateRegistries
|
train
|
private function updateRegistries($entities, $from)
{
if (count($entities) >= 0) {
for ($j = $from; $j >= 0; $j--) {
/** @var RegistryInterface $registry */
$registry = $this->registries[ $j ];
/** @var AbstractEntity $entity */
foreach ($entities as $entity) {
$registry->add($entity->getId(), $entity);
}
}
}
}
|
php
|
{
"resource": ""
}
|
q240922
|
Base.render
|
train
|
public function render()
{
$args = func_get_args();
foreach ($args as $arg) {
if(isset($this->output[$arg])) {
return $this->output[$arg];
}
throw new Exception("{$arg} is not set!", 1);
}
}
|
php
|
{
"resource": ""
}
|
q240923
|
Chain.addMapper
|
train
|
public function addMapper(ResultMapperInterface $mapper)
{
if ($mapper instanceof self) {
return $this->addMappers($mapper->mappers);
}
$this->mappers[] = $mapper;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240924
|
HasNullableFields.isValueChanged
|
train
|
public function isValueChanged($field)
{
if (!$this->IsNullable($field)) {
return false;
}
return isset($this->nullableChanged[$field]);
}
|
php
|
{
"resource": ""
}
|
q240925
|
HasNullableFields.nullableChanged
|
train
|
protected function nullableChanged($field = null)
{
if (!$field) {
$function = debug_backtrace()[1]['function'];
$field = lcfirst(substr($function, 3));
}
$this->nullableChanged[$field] = true;
}
|
php
|
{
"resource": ""
}
|
q240926
|
Database.newConnection
|
train
|
public function newConnection($host, $database, $user, $password)
{
return self::$driver->connect($host, $database, $user, $password);
}
|
php
|
{
"resource": ""
}
|
q240927
|
FileCache.persist
|
train
|
public function persist()
{
$parts = explode('/', $this->file);
array_pop($parts);
$dir = implode('/', $parts);
if (!is_dir($dir)) {
mkdir($dir, 493, true);
}
return file_put_contents($this->file, serialize($this->data));
}
|
php
|
{
"resource": ""
}
|
q240928
|
FileCache.rebuild
|
train
|
public function rebuild()
{
if (file_exists($this->file)) {
try {
$this->data = unserialize(file_get_contents($this->file));
return true;
} catch (\Exception $e) {
// Try just used to suppress the exception. If the cache is corrupted we just start from scratch.
}
}
$this->data = [];
$this->persist();
return false;
}
|
php
|
{
"resource": ""
}
|
q240929
|
IconsBuilder.build
|
train
|
public function build($basePath)
{
$cache = new PuliResourceCollectionCache($this->cacheDir.'gui-icons.css', $this->debug);
$resources = $this->resourceFinder->findByType('phlexible/icons');
if (!$cache->isFresh($resources)) {
$content = $this->buildIcons($resources, $basePath);
$cache->write($content);
if (!$this->debug) {
$this->compressor->compressFile((string) $cache);
}
}
return new Asset((string) $cache);
}
|
php
|
{
"resource": ""
}
|
q240930
|
Factory.getParameterListAsObject
|
train
|
public function getParameterListAsObject($name, $delimiter = ";")
{
$parameter = $this->getValidParameterOfType($name, "string");
$list = preg_split('/\s*(?:,*("[^"]+"),*|,*(\'[^\']+\'),*|,+)\s*/', $parameter, null,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
//if emptyparameter return throw an exception because they'd be expecting an object;
$parameters = [];
$values = [];
foreach ($list as $itemValue) {
//if items have qualities associated with them we shall sort the parameter array by qualities;
$bits = preg_split('/\s*(?:;*("[^"]+");*|;*(\'[^\']+\');*|;+)\s*/', $itemValue, 0,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$value = array_shift($bits);
$attributes = [];
$lastNullAttribute = null;
foreach ($bits as $bit) {
if (($start = substr($bit, 0, 1)) === ($end = substr($bit, -1))
&& ($start === '"'
|| $start === '\'')
) {
$attributes[$lastNullAttribute] = substr($bit, 1, -1);
} elseif ('=' === $end) {
$lastNullAttribute = $bit = substr($bit, 0, -1);
$attributes[$bit] = null;
} else {
$parts = explode('=', $bit);
$attributes[$parts[0]] = isset($parts[1]) && strlen($parts[1]) > 0 ? $parts[1] : '';
}
}
$parameters[($start = substr($value, 0, 1)) === ($end = substr($value, -1)) && ($start === '"' || $start === '\'')
? substr($value, 1, -1) : $value] = $attributes;
}
return new Factory($name, $parameters, static::$sanitizer, static::$validator, false);
}
|
php
|
{
"resource": ""
}
|
q240931
|
Toolbar.removeExtension
|
train
|
public function removeExtension($name)
{
if (isset($this->extensions[$name])) {
unset($this->extensions[$name]);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q240932
|
Core.javascriptRedirectUser
|
train
|
public static function javascriptRedirectUser($url, $numSeconds = 0)
{
$htmlString = '';
$htmlString .=
"<script type='text/javascript'>" .
"var redirectTime=" . $numSeconds * 1000 . ";" . PHP_EOL .
"var redirectURL='" . $url . "';" . PHP_EOL .
'setTimeout("location.href = redirectURL;", redirectTime);' . PHP_EOL .
"</script>";
return $htmlString;
}
|
php
|
{
"resource": ""
}
|
q240933
|
Core.setCliTitle
|
train
|
public static function setCliTitle($nameingPrefix)
{
$succeeded = false;
$num_running = self::getNumProcRunning($nameingPrefix);
if (function_exists('cli_set_process_title'))
{
cli_set_process_title($nameingPrefix . $num_running);
$succeeded = true;
}
return $succeeded;
}
|
php
|
{
"resource": ""
}
|
q240934
|
Core.sendApiRequest
|
train
|
public static function sendApiRequest($url, array $parameters, $requestType="POST", $headers=array())
{
$allowedRequestTypes = array("GET", "POST", "PUT", "PATCH", "DELETE");
$requestTypeUpper = strtoupper($requestType);
if (!in_array($requestTypeUpper, $allowedRequestTypes))
{
throw new \Exception("API request needs to be one of GET, POST, PUT, PATCH, or DELETE.");
}
if ($requestType === "GET")
{
$ret = self::sendGetRequest($url, $parameters);
}
else
{
$query_string = http_build_query($parameters, '', '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
switch ($requestTypeUpper)
{
case "POST":
{
curl_setopt($ch, CURLOPT_POST, 1);
}
break;
case "PUT":
case "PATCH":
case "DELETE":
{
curl_setopt($this->m_ch, CURLOPT_CUSTOMREQUEST, $requestTypeUpper);
}
break;
default:
{
throw new \Exception("Unrecognized request type.");
}
}
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
// @TODO - S.P. to review...
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// Manage if user provided headers.
if (count($headers) > 0)
{
$headersStrings = array();
foreach ($headers as $key=>$value)
{
$headersStrings[] = "{$key}: {$value}";
}
curl_setopt($this->m_ch, CURLOPT_HTTPHEADER, $this->m_headers);
}
$jsondata = curl_exec($ch);
if (curl_error($ch))
{
$errMsg = "Connection Error: " . curl_errno($ch) .
' - ' . curl_error($ch);
throw new \Exception($errMsg);
}
curl_close($ch);
$ret = json_decode($jsondata); # Decode JSON String
if ($ret == null)
{
$errMsg = 'Recieved a non json response from API: ' . $jsondata;
throw new \Exception($errMsg);
}
}
return $ret;
}
|
php
|
{
"resource": ""
}
|
q240935
|
Core.sendGetRequest
|
train
|
public static function sendGetRequest($url, array $parameters=array(), $arrayForm=false)
{
if (count($parameters) > 0)
{
$query_string = http_build_query($parameters, '', '&');
$url .= $query_string;
}
# Get cURL resource
$curl = curl_init();
# Set some options - we are passing in a useragent too here
$curlOptions = array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
);
curl_setopt_array($curl, $curlOptions);
# Send the request
$rawResponse = curl_exec($curl);
# Close request to clear up some resources
curl_close($curl);
# Convert to json object.
$responseObj = json_decode($rawResponse, $arrayForm); # Decode JSON String
if ($responseObj == null)
{
$errMsg = 'Recieved a non json response from API: ' . $rawResponse;
throw new \Exception($errMsg);
}
return $responseObj;
}
|
php
|
{
"resource": ""
}
|
q240936
|
Core.fetchArgs
|
train
|
public static function fetchArgs(array $reqArgs, array $optionalArgs)
{
$values = self::fetchReqArgs($reqArgs);
$values = array_merge($values, self::fetchOptionalArgs($optionalArgs));
return $values;
}
|
php
|
{
"resource": ""
}
|
q240937
|
Core.getCurrentUrl
|
train
|
public static function getCurrentUrl()
{
$pageURL = 'http';
if (isset($_SERVER["HTTPS"]))
{
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"] . ":" .
$_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}
|
php
|
{
"resource": ""
}
|
q240938
|
Core.versionGuard
|
train
|
public static function versionGuard($reqVersion, $errMsg='')
{
if (version_compare(PHP_VERSION, $reqVersion) == -1)
{
if ($errMsg == '')
{
$errMsg = 'Required PHP version: ' . $reqVersion .
', current Version: ' . PHP_VERSION;
}
die($errMsg);
}
}
|
php
|
{
"resource": ""
}
|
q240939
|
Core.isPortOpen
|
train
|
public static function isPortOpen($host, $port, $protocol)
{
$protocol = strtolower($protocol);
if ($protocol != 'tcp' && $protocol != 'udp')
{
$errMsg = 'Unrecognized protocol [' . $protocol . '] ' .
'please specify [tcp] or [udp]';
throw new \Exception($errMsg);
}
if (empty($host))
{
$host = self::getPublicIp();
}
foreach ($ports as $port)
{
$connection = @fsockopen($host, $port);
if (is_resource($connection))
{
$isOpen = true;
fclose($connection);
}
else
{
$isOpen = false;
}
}
return $isOpen;
}
|
php
|
{
"resource": ""
}
|
q240940
|
Core.generateConfig
|
train
|
public static function generateConfig($settings, $variableName, $filePath)
{
$varStr = var_export($settings, true);
$output =
'<?php' . PHP_EOL .
'$' . $variableName . ' = ' . $varStr . ';';
# file_put_contents returns num bytes written or boolean false if fail
$wroteFile = file_put_contents($filePath, $output);
if ($wroteFile === FALSE)
{
$msg = "Failed to generate config file. Check permissions!";
throw new \Exception($msg);
}
}
|
php
|
{
"resource": ""
}
|
q240941
|
Core.generatePasswordHash
|
train
|
public static function generatePasswordHash($rawPassword, $cost=11)
{
$cost = intval($cost);
$cost = self::clampValue($cost, $max=31, $min=4);
# has to be 2 digits, eg. 04
if ($cost < 10)
{
$cost = "0" . $cost;
}
$options = array('cost' => $cost);
$hash = password_hash($rawPassword, PASSWORD_BCRYPT, $options);
return $hash;
}
|
php
|
{
"resource": ""
}
|
q240942
|
Core.isValidSignedRequest
|
train
|
public static function isValidSignedRequest(array $data, string $signature)
{
$generated_signature = SiteSpecific::generateSignature($data);
return ($generated_signature == $signature);
}
|
php
|
{
"resource": ""
}
|
q240943
|
ButtonGroup.button
|
train
|
public function button(
$label = null,
$url = null,
$status = null,
$icon = null,
$block = false,
$disabled = false,
$flat = false,
$size = Button::SIZE_NORMAL)
{
$button = new Button($label, $url, $status, $icon, $block, $disabled, $flat, $size);
return $this->addButton($button);
}
|
php
|
{
"resource": ""
}
|
q240944
|
CpeLogger.logOut
|
train
|
public function logOut(
$type,
$source,
$message,
$logKey = null,
$printOut = true)
{
$log = [
"time" => date("Y-m-d H:i:s", time()),
"source" => $source,
"type" => $type,
"message" => $message
];
if ($printOut)
$this->printOut = $printOut;
if ($logKey)
$log["logKey"] = $logKey;
// Set the log filaname based on the logkey If provided.
// If not then it will log in a file that has the name of the PHP activity file
$file = $this->activityName;
// Append progname to the path
$this->filePath = $this->logPath . "/" . $file.".log";
// Open Syslog. Use programe name as key
if (!openlog (__FILE__, LOG_CONS|LOG_PID, LOG_LOCAL1))
throw new CpeException("Unable to connect to Syslog!",
OPENLOG_ERROR);
// Change Syslog priority level
switch ($type)
{
case "INFO":
$priority = LOG_INFO;
break;
case "ERROR":
$priority = LOG_ERR;
break;
case "FATAL":
$priority = LOG_ALERT;
break;
case "WARNING":
$priority = LOG_WARNING;
break;
case "DEBUG":
$priority = LOG_DEBUG;
break;
default:
throw new CpeException("Unknown log Type!",
LOG_TYPE_ERROR);
}
// Print log in file
$this->printToFile($log);
// Encode log message in JSON for better parsing
$out = json_encode($log);
// Send to syslog
syslog($priority, $out);
}
|
php
|
{
"resource": ""
}
|
q240945
|
CpeLogger.printToFile
|
train
|
private function printToFile($log)
{
if (!is_string($log['message']))
$log['message'] = json_encode($log['message']);
$toPrint = $log['time'] . " [" . $log['type'] . "] [" . $log['source'] . "] ";
// If there is a workflow ID. We append it.
if (isset($log['logKey']) && $log['logKey'])
$toPrint .= "[".$log['logKey']."] ";
$toPrint .= $log['message'] . "\n";
if ($this->printout)
print $toPrint;
if (file_put_contents(
$this->filePath,
$toPrint,
FILE_APPEND) === false) {
throw new CpeException("Can't write into log file: $this->logPath",
LOGFILE_ERROR);
}
}
|
php
|
{
"resource": ""
}
|
q240946
|
Enum.fromString
|
train
|
final public static function fromString(string $string): Enum
{
$parts = explode('::', $string);
return self::fromName(end($parts));
}
|
php
|
{
"resource": ""
}
|
q240947
|
Enum.fromName
|
train
|
final public static function fromName(string $name): Enum
{
$constName = sprintf('%s::%s', static::class, $name);
if (!defined($constName)) {
$message = sprintf('%s is not a member constant of enum %s', $name, static::class);
throw new DomainException($message);
}
return new static(constant($constName));
}
|
php
|
{
"resource": ""
}
|
q240948
|
Enum.fromOrdinal
|
train
|
final public static function fromOrdinal(int $ordinal): Enum
{
$constants = self::getMembers();
$item = array_slice($constants, $ordinal, 1, true);
if (!$item) {
$end = count($constants) - 1;
$message = sprintf('Enum ordinal (%d) out of range [0, %d]', $ordinal, $end);
throw new DomainException($message);
}
return new static(current($item));
}
|
php
|
{
"resource": ""
}
|
q240949
|
Enum.getMembers
|
train
|
final public static function getMembers(): array
{
if (!isset(self::$constants[static::class])) {
$reflection = new ReflectionClass(static::class);
$constants = self::sortConstants($reflection);
self::guardConstants($constants);
self::$constants[static::class] = $constants;
}
return self::$constants[static::class];
}
|
php
|
{
"resource": ""
}
|
q240950
|
Enum.name
|
train
|
final public function name(): string
{
if ($this->name === null) {
$constants = self::getMembers();
$this->name = array_search($this->value, $constants, true);
}
return $this->name;
}
|
php
|
{
"resource": ""
}
|
q240951
|
Enum.ordinal
|
train
|
final public function ordinal(): int
{
if ($this->ordinal === null) {
$ordinal = 0;
foreach (self::getMembers() as $constValue) {
if ($this->value === $constValue) {
break;
}
$ordinal++;
}
$this->ordinal = $ordinal;
}
return $this->ordinal;
}
|
php
|
{
"resource": ""
}
|
q240952
|
Enum.guardConstants
|
train
|
final private static function guardConstants(array $constants): void
{
$duplicates = [];
foreach ($constants as $value) {
$names = array_keys($constants, $value, $strict = true);
if (count($names) > 1) {
$duplicates[VarPrinter::toString($value)] = $names;
}
}
if (!empty($duplicates)) {
$list = array_map(function ($names) use ($constants) {
return sprintf('(%s)=%s', implode('|', $names), VarPrinter::toString($constants[$names[0]]));
}, $duplicates);
$message = sprintf('Duplicate enum values: %s', implode(', ', $list));
throw new DomainException($message);
}
}
|
php
|
{
"resource": ""
}
|
q240953
|
Enum.sortConstants
|
train
|
final private static function sortConstants(ReflectionClass $reflection): array
{
$constants = [];
while ($reflection && __CLASS__ !== $reflection->getName()) {
$scope = [];
foreach ($reflection->getReflectionConstants() as $const) {
if ($const->isPublic()) {
$scope[$const->getName()] = $const->getValue();
}
}
$constants = $scope + $constants;
$reflection = $reflection->getParentClass();
}
return $constants;
}
|
php
|
{
"resource": ""
}
|
q240954
|
Validator.getValidation
|
train
|
private function getValidation(string $name): validator\Validation
{
if (!isset($this->validations[$name])) {
if (isset($this->validationRegister[$name])) {
$class = $this->validationRegister[$name];
} else {
throw new exceptions\ValidatorException("Validator [$name] not found");
}
$params = isset($this->validationData[$name]) ? $this->validationData[$name] : null;
$this->validations[$name] = new $class($params);
}
return $this->validations[$name];
}
|
php
|
{
"resource": ""
}
|
q240955
|
Validator.registerValidation
|
train
|
protected function registerValidation(string $name, string $class, $data = null)
{
$this->validationRegister[$name] = $class;
$this->validationData[$name] = $data;
}
|
php
|
{
"resource": ""
}
|
q240956
|
Validator.getFieldInfo
|
train
|
private function getFieldInfo($key, $value): array
{
$name = null;
$options = [];
if (is_numeric($key) && is_string($value)) {
$name = $value;
} else if (is_numeric($key) && is_array($value)) {
$name = array_shift($value);
$options = $value;
} else if (is_string($key)) {
$name = $key;
$options = $value;
}
return ['name' => $name, 'options' => $options];
}
|
php
|
{
"resource": ""
}
|
q240957
|
Validator.validate
|
train
|
public function validate(array $data) : bool
{
$passed = true;
$this->invalidFields = [];
$rules = $this->getRules();
foreach ($rules as $validation => $fields) {
foreach ($fields as $key => $value) {
$field = $this->getFieldInfo($key, $value);
$validationInstance = $this->getValidation($validation);
$validationStatus = $validationInstance->run($field, $data);
$passed = $passed && $validationStatus;
$this->invalidFields = array_merge_recursive(
$this->invalidFields, $validationInstance->getMessages()
);
}
}
return $passed;
}
|
php
|
{
"resource": ""
}
|
q240958
|
Lagan.universalCreate
|
train
|
protected function universalCreate() {
$bean = \R::dispense($this->type);
$bean->created = \R::isoDateTime();
return $bean;
}
|
php
|
{
"resource": ""
}
|
q240959
|
Lagan.set
|
train
|
public function set($data, $bean) {
// Add all properties to bean
foreach ( $this->properties as $property ) {
$value = false; // We need to clear possible previous $value
// Define property controller
$c = new $property['type'];
// New input for the property
if (
isset( $data[ $property['name'] ] )
||
( isset( $_FILES[ $property['name'] ] ) && $_FILES[ $property['name'] ]['size'] > 0 )
||
$property['autovalue'] == true
) {
// Check if specific set property type method exists
if ( method_exists( $c, 'set' ) ) {
$value = $c->set( $bean, $property, $data[ $property['name'] ] );
} else {
$value = $data[ $property['name'] ];
}
if ($value) {
$hasvalue = true;
} else {
$hasvalue = false;
}
// No new input for the property
} else {
// Check if property already has value for required validation
if ( isset( $property['required'] ) ) {
if ( method_exists( $c, 'read' ) && $c->read( $bean, $property ) ) {
$hasvalue = true;
} else if ( $bean->{ $property['name'] } ) {
$hasvalue = true;
} else {
$hasvalue = false;
}
}
}
// Check if property is required
if ( isset( $property['required'] ) ) {
if ( $property['required'] && !$hasvalue ) {
throw new \Exception('Validation error. '.$property['description'].' is required.');
}
}
// Results from methods that return boolean values are not stored.
// Many-to-many relations for example are stored in a seperate table.
if ( !is_bool($value) ) {
// Check if property value is unique
if ( isset( $property['unique'] ) ) {
$duplicate = \R::findOne( $this->type, $property['name'].' = :val ', [ ':val' => $value ] );
if ( $duplicate && $duplicate->id != $bean->id ) {
throw new \Exception('Validation error. '.$property['description'].' should be unique.');
}
}
$bean->{ $property['name'] } = $value;
}
}
$bean->modified = \R::isoDateTime();
\R::store($bean);
return $bean;
}
|
php
|
{
"resource": ""
}
|
q240960
|
ChainProvider.tryGetValue
|
train
|
protected static function tryGetValue($provider, $object, $propertyName, &$error)
{
try {
return call_user_func(array($provider, 'getValue'), $object, $propertyName);
} catch (\InvalidArgumentException $e) {
$error = $e;
return null;
}
}
|
php
|
{
"resource": ""
}
|
q240961
|
ChainProvider.trySetValue
|
train
|
protected static function trySetValue($provider, &$object, $propertyName, $value, &$error)
{
try {
return call_user_func(array($provider, 'setValue'), $object, $propertyName, $value);
} catch (\InvalidArgumentException $e) {
$error = $e;
return null;
}
}
|
php
|
{
"resource": ""
}
|
q240962
|
Behavior.canGetProperty
|
train
|
public function canGetProperty($name, $checkVars = true)
{
if (!in_array($name, $this->attrs)) {
return parent::canGetProperty($name, $checkVars);
}
return true;
}
|
php
|
{
"resource": ""
}
|
q240963
|
Behavior.events
|
train
|
public function events()
{
return [
\yii\db\ActiveRecord::EVENT_BEFORE_VALIDATE => 'handleValidate',
\yii\db\ActiveRecord::EVENT_AFTER_INSERT => 'handleAfterSave',
\yii\db\ActiveRecord::EVENT_AFTER_UPDATE => 'handleAfterSave',
];
}
|
php
|
{
"resource": ""
}
|
q240964
|
Behavior.interpreter
|
train
|
public function interpreter(array $restriction = [])
{
if (null === $this->_interpreter) {
$this->_interpreter = new Interpreter($this->owner, $this->config, $this->allowCache, $this->attrActive);
}
$this->_interpreter->setRestriction($restriction);
return $this->_interpreter;
}
|
php
|
{
"resource": ""
}
|
q240965
|
Zend_Gdata_Photos.getUserFeed
|
train
|
public function getUserFeed($userName = null, $location = null)
{
if ($location instanceof Zend_Gdata_Photos_UserQuery) {
$location->setType('feed');
if ($userName !== null) {
$location->setUser($userName);
}
$uri = $location->getQueryUrl();
} else if ($location instanceof Zend_Gdata_Query) {
if ($userName !== null) {
$location->setUser($userName);
}
$uri = $location->getQueryUrl();
} else if ($location !== null) {
$uri = $location;
} else if ($userName !== null) {
$uri = self::PICASA_BASE_FEED_URI . '/' .
self::DEFAULT_PROJECTION . '/' . self::USER_PATH . '/' .
$userName;
} else {
$uri = self::PICASA_BASE_FEED_URI . '/' .
self::DEFAULT_PROJECTION . '/' . self::USER_PATH . '/' .
self::DEFAULT_USER;
}
return parent::getFeed($uri, 'Zend_Gdata_Photos_UserFeed');
}
|
php
|
{
"resource": ""
}
|
q240966
|
Zend_Gdata_Photos.getAlbumFeed
|
train
|
public function getAlbumFeed($location = null)
{
if ($location === null) {
require_once 'Zend/Gdata/App/InvalidArgumentException.php';
throw new Zend_Gdata_App_InvalidArgumentException(
'Location must not be null');
} else if ($location instanceof Zend_Gdata_Photos_UserQuery) {
$location->setType('feed');
$uri = $location->getQueryUrl();
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_Photos_AlbumFeed');
}
|
php
|
{
"resource": ""
}
|
q240967
|
Zend_Gdata_Photos.getPhotoFeed
|
train
|
public function getPhotoFeed($location = null)
{
if ($location === null) {
$uri = self::PICASA_BASE_FEED_URI . '/' .
self::DEFAULT_PROJECTION . '/' .
self::COMMUNITY_SEARCH_PATH;
} else if ($location instanceof Zend_Gdata_Photos_UserQuery) {
$location->setType('feed');
$uri = $location->getQueryUrl();
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getFeed($uri, 'Zend_Gdata_Photos_PhotoFeed');
}
|
php
|
{
"resource": ""
}
|
q240968
|
Zend_Gdata_Photos.getUserEntry
|
train
|
public function getUserEntry($location)
{
if ($location === null) {
require_once 'Zend/Gdata/App/InvalidArgumentException.php';
throw new Zend_Gdata_App_InvalidArgumentException(
'Location must not be null');
} else if ($location instanceof Zend_Gdata_Photos_UserQuery) {
$location->setType('entry');
$uri = $location->getQueryUrl();
} else if ($location instanceof Zend_Gdata_Query) {
$uri = $location->getQueryUrl();
} else {
$uri = $location;
}
return parent::getEntry($uri, 'Zend_Gdata_Photos_UserEntry');
}
|
php
|
{
"resource": ""
}
|
q240969
|
Zend_Gdata_Photos.insertAlbumEntry
|
train
|
public function insertAlbumEntry($album, $uri = null)
{
if ($uri === null) {
$uri = self::PICASA_BASE_FEED_URI . '/' .
self::DEFAULT_PROJECTION . '/' . self::USER_PATH . '/' .
self::DEFAULT_USER;
}
$newEntry = $this->insertEntry($album, $uri, 'Zend_Gdata_Photos_AlbumEntry');
return $newEntry;
}
|
php
|
{
"resource": ""
}
|
q240970
|
Zend_Gdata_Photos.insertPhotoEntry
|
train
|
public function insertPhotoEntry($photo, $uri = null)
{
if ($uri instanceof Zend_Gdata_Photos_AlbumEntry) {
$uri = $uri->getLink(self::FEED_LINK_PATH)->href;
}
if ($uri === null) {
require_once 'Zend/Gdata/App/InvalidArgumentException.php';
throw new Zend_Gdata_App_InvalidArgumentException(
'URI must not be null');
}
$newEntry = $this->insertEntry($photo, $uri, 'Zend_Gdata_Photos_PhotoEntry');
return $newEntry;
}
|
php
|
{
"resource": ""
}
|
q240971
|
Zend_Gdata_Photos.insertTagEntry
|
train
|
public function insertTagEntry($tag, $uri = null)
{
if ($uri instanceof Zend_Gdata_Photos_PhotoEntry) {
$uri = $uri->getLink(self::FEED_LINK_PATH)->href;
}
if ($uri === null) {
require_once 'Zend/Gdata/App/InvalidArgumentException.php';
throw new Zend_Gdata_App_InvalidArgumentException(
'URI must not be null');
}
$newEntry = $this->insertEntry($tag, $uri, 'Zend_Gdata_Photos_TagEntry');
return $newEntry;
}
|
php
|
{
"resource": ""
}
|
q240972
|
Zend_Gdata_Photos.insertCommentEntry
|
train
|
public function insertCommentEntry($comment, $uri = null)
{
if ($uri instanceof Zend_Gdata_Photos_PhotoEntry) {
$uri = $uri->getLink(self::FEED_LINK_PATH)->href;
}
if ($uri === null) {
require_once 'Zend/Gdata/App/InvalidArgumentException.php';
throw new Zend_Gdata_App_InvalidArgumentException(
'URI must not be null');
}
$newEntry = $this->insertEntry($comment, $uri, 'Zend_Gdata_Photos_CommentEntry');
return $newEntry;
}
|
php
|
{
"resource": ""
}
|
q240973
|
Zend_Gdata_Photos.deleteAlbumEntry
|
train
|
public function deleteAlbumEntry($album, $catch)
{
if ($catch) {
try {
$this->delete($album);
} catch (Zend_Gdata_App_HttpException $e) {
if ($e->getResponse()->getStatus() === 409) {
$entry = new Zend_Gdata_Photos_AlbumEntry($e->getResponse()->getBody());
$this->delete($entry->getLink('edit')->href);
} else {
throw $e;
}
}
} else {
$this->delete($album);
}
}
|
php
|
{
"resource": ""
}
|
q240974
|
Zend_Gdata_Photos.deletePhotoEntry
|
train
|
public function deletePhotoEntry($photo, $catch)
{
if ($catch) {
try {
$this->delete($photo);
} catch (Zend_Gdata_App_HttpException $e) {
if ($e->getResponse()->getStatus() === 409) {
$entry = new Zend_Gdata_Photos_PhotoEntry($e->getResponse()->getBody());
$this->delete($entry->getLink('edit')->href);
} else {
throw $e;
}
}
} else {
$this->delete($photo);
}
}
|
php
|
{
"resource": ""
}
|
q240975
|
Zend_Gdata_Photos.deleteCommentEntry
|
train
|
public function deleteCommentEntry($comment, $catch)
{
if ($catch) {
try {
$this->delete($comment);
} catch (Zend_Gdata_App_HttpException $e) {
if ($e->getResponse()->getStatus() === 409) {
$entry = new Zend_Gdata_Photos_CommentEntry($e->getResponse()->getBody());
$this->delete($entry->getLink('edit')->href);
} else {
throw $e;
}
}
} else {
$this->delete($comment);
}
}
|
php
|
{
"resource": ""
}
|
q240976
|
Zend_Gdata_Photos.deleteTagEntry
|
train
|
public function deleteTagEntry($tag, $catch)
{
if ($catch) {
try {
$this->delete($tag);
} catch (Zend_Gdata_App_HttpException $e) {
if ($e->getResponse()->getStatus() === 409) {
$entry = new Zend_Gdata_Photos_TagEntry($e->getResponse()->getBody());
$this->delete($entry->getLink('edit')->href);
} else {
throw $e;
}
}
} else {
$this->delete($tag);
}
}
|
php
|
{
"resource": ""
}
|
q240977
|
En_CronRequest.getParam
|
train
|
public function getParam($index){
if(isset($this->params[$index])){
return $this->params[$index];
}else{
return NULL;
}
}
|
php
|
{
"resource": ""
}
|
q240978
|
En_CronRequest.getParamClean
|
train
|
public function getParamClean($index){
if(isset($this->params[$index])){
return $this->params[$index];
}else{
return NULL;
}
}
|
php
|
{
"resource": ""
}
|
q240979
|
En_CronRequest.getParamAll
|
train
|
public function getParamAll($index){
if(isset($this->allParams[$index])){
return Security::clean_vars($this->allParams[$index]);
}
else{
return NULL;
}
}
|
php
|
{
"resource": ""
}
|
q240980
|
En_CronRequest.getParamAllClean
|
train
|
public function getParamAllClean($index){
if(isset($this->allParams[$index])){
return Security::clean_vars($this->allParams[$index]);
}
else{
return NULL;
}
}
|
php
|
{
"resource": ""
}
|
q240981
|
Filter.build
|
train
|
protected function build($m)
{
$string = $m[1];
if (substr($string, 0, 1) != '<') {
// We matched a lone ">" character.
return '>';
} elseif (strlen($string) == 1) {
// We matched a lone "<" character.
return '<';
}
if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
// Seriously malformed.
return '';
}
$slash = trim($matches[1]);
$elem = &$matches[2];
$attrlist = &$matches[3];
$comment = &$matches[4];
if ($comment) {
$elem = '!--';
}
if (!in_array(strtolower($elem), $this->tags, true)) {
return ''; // Disallowed HTML element.
}
if ($comment) {
return $comment;
}
if ($slash != '') {
return "</$elem>";
}
// Is there a closing XHTML slash at the end of the attributes?
$attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
$xhtml_slash = $count ? ' /' : '';
// Clean up attributes.
$attr2 = implode(' ', $this->explodeAttributes($attrlist));
$attr2 = preg_replace('/[<>]/', '', $attr2);
$attr2 = strlen($attr2) ? ' ' . $attr2 : '';
return "<$elem$attr2$xhtml_slash>";
}
|
php
|
{
"resource": ""
}
|
q240982
|
ArrArgumentsDescriptor.match
|
train
|
public function match($var)
{
$ret = false;
foreach ($this->_types as $type) {
if (array_search($type, array("*", "mixed")) !== false) {
$ret = true;
} elseif (array_search($type, array("number", "numeric")) !== false) {
$ret = is_numeric($var);
} elseif (array_search($type, array("bool", "boolean")) !== false) {
$ret = is_bool($var);
} elseif ($type == "string") {
$ret = is_string($var);
} elseif ($type == "array") {
$ret = is_array($var);
} elseif ($type == "object") {
$ret = is_object($var);
} elseif ($type == "resource") {
$ret = is_resource($var);
} elseif ($type == "function") {
$ret = is_callable($var);
} elseif ($type == "scalar") {
$ret = is_scalar($var);
} else {
$ret = is_a($var, $type);
}
if ($ret) {
break;
}
}
return $ret;
}
|
php
|
{
"resource": ""
}
|
q240983
|
Middleware.execute
|
train
|
public function execute()
{
if (is_string($this->callback)) {
// Will call the controller here
$parts = explode('::', $this->callback);
$className = $parts[0];
$classMethod = $parts[1];
if (! class_exists($className)) {
throw new RouterException("The callback class declared in your middleware is not found: '{$className}'");
}
$class = new $className();
if (! $class instanceof BaseMiddleware) {
throw new RouterException("The class in your middleware route doesn't extend the BaseMiddleware: '{$className}'"); // @codeCoverageIgnore
}
if (! method_exists($class, $classMethod)) {
throw new RouterException("The class in your middleware route doesn't have the method you provided: '{$className}' method: {$classMethod}");
}
// Call the method. Catch return
$result = call_user_func(array($class, $classMethod));
} elseif (is_callable($this->callback)) {
$result = call_user_func($this->callback);
} else {
throw new RouterException("Middleware callback is not a class or callable!"); // @codeCoverageIgnore
}
// See if we got a boolean back.
if ($result === false && $this->position === 'before') {
// We should stop!
return false;
}
return true;
}
|
php
|
{
"resource": ""
}
|
q240984
|
Network.prepare
|
train
|
public function prepare()
{
$class = get_class($this);
// Check table
if (!isset($this->dbTable)) {
return e('Cannot load "'.$class.'" module - no $dbTable is configured');
}
// Social system specific configuration check
if ($class != __CLASS__) {
db()->createField($this, $this->dbTable, 'dbIdField', 'VARCHAR(50)');
}
// Create and check general database table fields configuration
db()->createField($this, $this->dbTable, 'dbNameField', 'VARCHAR(50)');
db()->createField($this, $this->dbTable, 'dbSurnameField', 'VARCHAR(50)');
db()->createField($this, $this->dbTable, 'dbEmailField', 'VARCHAR(50)');
db()->createField($this, $this->dbTable, 'dbGenderField', 'VARCHAR(10)');
db()->createField($this, $this->dbTable, 'dbBirthdayField', 'DATE');
db()->createField($this, $this->dbTable, 'dbPhotoField', 'VARCHAR(125)');
return parent::prepare();
}
|
php
|
{
"resource": ""
}
|
q240985
|
Network.init
|
train
|
public function init(array $params = array())
{
// Try to load token from session
if (isset($_SESSION[self::SESSION_PREFIX.'_'.$this->id])) {
$this->token = $_SESSION[self::SESSION_PREFIX.'_'.$this->id];
}
parent::init($params);
}
|
php
|
{
"resource": ""
}
|
q240986
|
Network.setUser
|
train
|
protected function setUser(array $userData, & $user = null)
{
// Generic birthdate parsing
$user->birthday = date('Y-m-d H:i:s', strtotime($user->birthday));
// If no external user is passed set as current user
if (isset($user)) {
$this->user = & $user;
}
}
|
php
|
{
"resource": ""
}
|
q240987
|
Network.&
|
train
|
protected function & storeUserData(&$user = null)
{
// If no user is passed - create it
if (!isset($user)) {
$user = new $this->dbTable(false);
}
// Store social data for user
$user[$this->dbIdField] = $this->user->socialID;
$user[$this->dbNameField] = strlen($this->user->name) ? $this->user->name : $user[$this->dbNameField];
$user[$this->dbSurnameField] = strlen($this->user->surname) ? $this->user->surname : $user[$this->dbSurnameField] ;
$user[$this->dbGenderField] = strlen($this->user->gender) ? $this->user->gender : $user[$this->dbGenderField] ;
$user[$this->dbBirthdayField] = max($user[$this->dbBirthdayField],$this->user->birthday);
$user[$this->dbPhotoField] = strlen($this->user->photo) ? $this->user->photo : $user[$this->dbPhotoField];
// If no email is passed - set hashed socialID as email
if (!strlen($this->user->email)) {
if (!strlen($user->email)) {
$user[$this->dbEmailField] = md5($this->user->socialID);
}
} else {
$user[$this->dbEmailField] = $this->user->email;
}
$user->save();
return $user;
}
|
php
|
{
"resource": ""
}
|
q240988
|
Network.&
|
train
|
public function & friends($count = null, $offset = null)
{
$result = array();
// If we have authorized via one of social modules
if (isset($this->active)) {
// Call friends method on active social module
$result = & $this->active->friends($count, $offset);
}
return $result;
}
|
php
|
{
"resource": ""
}
|
q240989
|
SpamModel.IsSpam
|
train
|
public static function IsSpam($RecordType, $Data, $Options = array()) {
if (self::$Disabled)
return FALSE;
// Set some information about the user in the data.
if ($RecordType == 'Registration') {
TouchValue('Username', $Data, $Data['Name']);
} else {
TouchValue('InsertUserID', $Data, Gdn::Session()->UserID);
$User = Gdn::UserModel()->GetID(GetValue('InsertUserID', $Data), DATASET_TYPE_ARRAY);
if ($User) {
if (GetValue('Verified', $User)) {
// The user has been verified and isn't a spammer.
return FALSE;
}
TouchValue('Username', $Data, $User['Name']);
TouchValue('Email', $Data, $User['Email']);
TouchValue('IPAddress', $Data, $User['LastIPAddress']);
}
}
if (!isset($Data['Body']) && isset($Data['Story'])) {
$Data['Body'] = $Data['Story'];
}
TouchValue('IPAddress', $Data, Gdn::Request()->IpAddress());
$Sp = self::_Instance();
$Sp->EventArguments['RecordType'] = $RecordType;
$Sp->EventArguments['Data'] =& $Data;
$Sp->EventArguments['Options'] =& $Options;
$Sp->EventArguments['IsSpam'] = FALSE;
$Sp->FireEvent('CheckSpam');
$Spam = $Sp->EventArguments['IsSpam'];
// Log the spam entry.
if ($Spam && GetValue('Log', $Options, TRUE)) {
$LogOptions = array();
switch ($RecordType) {
case 'Registration':
$LogOptions['GroupBy'] = array('RecordIPAddress');
break;
case 'Comment':
case 'Discussion':
case 'Activity':
case 'ActivityComment':
$LogOptions['GroupBy'] = array('RecordID');
break;
}
LogModel::Insert('Spam', $RecordType, $Data, $LogOptions);
}
return $Spam;
}
|
php
|
{
"resource": ""
}
|
q240990
|
Navigation.clear
|
train
|
public static function clear($path = null) {
if (empty($path)) {
self::$_items = array();
return;
}
if (Hash::check(self::$_items, $path)) {
self::$_items = Hash::insert(self::$_items, $path, array());
}
}
|
php
|
{
"resource": ""
}
|
q240991
|
Navigation.order
|
train
|
public static function order($items) {
if (empty($items)) {
return array();
}
$_items = array_combine(array_keys($items), Hash::extract($items, '{s}.weight'));
asort($_items);
foreach (array_keys($_items) as $key) {
$_items[$key] = $items[$key];
}
return $items;
}
|
php
|
{
"resource": ""
}
|
q240992
|
InheritanceFinder.findMultiple
|
train
|
public function findMultiple($classes = [], $interfaces = [], $traits = []) {
$this->init();
$classes = $this->normalizeArray($classes);
$interfaces = $this->normalizeArray($interfaces);
$traits = $this->normalizeArray($traits);
$foundClasses = [];
if ($classes !== false) {
foreach ($classes as $class) {
$foundClasses = array_merge($foundClasses, $this->findExtends($class));
}
}
if ($interfaces !== false) {
foreach ($interfaces as $interface) {
$foundClasses = array_merge($foundClasses, $this->findImplements($interface));
}
}
if ($traits !== false) {
foreach ($traits as $trait) {
$foundClasses = array_merge($foundClasses, $this->findTraitUse($trait));
}
}
return $this->arrayUniqueObject($foundClasses);
}
|
php
|
{
"resource": ""
}
|
q240993
|
InheritanceFinder.findImplementsOrTraitUse
|
train
|
protected function findImplementsOrTraitUse($fullQualifiedNamespace, $type) {
$fullQualifiedNamespace = $this->trimNamespace($fullQualifiedNamespace);
$phpClasses = [];
$method = 'get' . ucfirst($type);
foreach ($this->localCache as $phpClass) {
$implementsOrTrait = $phpClass->$method();
if (is_array($implementsOrTrait) && in_array($fullQualifiedNamespace, $implementsOrTrait)) {
$phpClasses[] = $phpClass;
$phpClasses = array_merge($phpClasses, $this->findExtends($phpClass->getFullQualifiedNamespace()));
}
}
return $this->arrayUniqueObject($phpClasses);
}
|
php
|
{
"resource": ""
}
|
q240994
|
InheritanceFinder.arrayUniqueObject
|
train
|
protected function arrayUniqueObject($phpClasses) {
$hashes = [];
foreach ($phpClasses as $key => $phpClass) {
$hashes[$key] = spl_object_hash($phpClass);
}
$hashes = array_unique($hashes);
$uniqueArray = [];
foreach ($hashes as $key => $hash) {
$uniqueArray[$key] = $phpClasses[$key];
}
return $uniqueArray;
}
|
php
|
{
"resource": ""
}
|
q240995
|
AbstractArray.getValue
|
train
|
public function getValue($key) {
if (isset ( $this->a [$key] )) {
return $this->a [$key];
} else {
return NULL;
}
}
|
php
|
{
"resource": ""
}
|
q240996
|
LangJsGenerator.getMessagesFromSourcePath
|
train
|
protected function getMessagesFromSourcePath($path, $namespace)
{
$messages = [];
if (! $this->file->exists($path)) {
throw new \Exception("${path} doesn't exists!");
}
foreach ($this->file->allFiles($path) as $file) {
$pathName = $file->getRelativePathName();
if ($this->file->extension($pathName) !== 'php') {
continue;
}
$key = substr($pathName, 0, -4);
$key = str_replace('\\', '.', $key);
$key = str_replace('/', '.', $key);
$array = explode('.', $key, 2);
$keyWithNamespace = $array[0].'.'.$namespace.'::'.$array[1];
$messages[$keyWithNamespace] = include "${path}/${pathName}";
}
return $messages;
}
|
php
|
{
"resource": ""
}
|
q240997
|
LangJsGenerator.prepareTarget
|
train
|
protected function prepareTarget($target)
{
$dirname = dirname($target);
if (! $this->file->exists($dirname)) {
$this->file->makeDirectory($dirname);
}
}
|
php
|
{
"resource": ""
}
|
q240998
|
AuthorizationCode.redirect
|
train
|
public static function redirect(Url $url, $clientId, $redirectUri = null, $scope = null, $state = null)
{
$parameters = $url->getParameters();
$parameters['response_type'] = 'code';
$parameters['client_id'] = $clientId;
if (isset($redirectUri)) {
$parameters['redirect_uri'] = $redirectUri;
}
if (isset($scope)) {
$parameters['scope'] = $scope;
}
if (isset($state)) {
$parameters['state'] = $state;
}
throw new StatusCode\TemporaryRedirectException($url->withScheme('https')->withParameters($parameters)->toString());
}
|
php
|
{
"resource": ""
}
|
q240999
|
CharCount.count
|
train
|
public static function count(string $text = '', bool $includeSpaces = false): int
{
if (\trim($text) === '') {
return 0;
}
$text = StripTags::strip($text);
$text = \htmlspecialchars_decode((string)$text, ENT_COMPAT | ENT_HTML5);
$text = \preg_replace('/\s+/', $includeSpaces ? ' ' : '', $text);
$text = \trim($text);
return \mb_strlen($text, 'UTF-8');
}
|
php
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.