_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q266200 | Journal.addSuccess | test | public function addSuccess($time)
{
$total = ( $this->data['avg'] * $this->data['works'] ) + $time;
$this->data['works']++;
$this->data['avg'] = $total/$this->data['works'];
return $this->data['works'];
} | php | {
"resource": ""
} |
q266201 | Journal.addIdle | test | public function addIdle()
{
$time = microtime(true) - $this->idleSince;
$this->idleSince = microtime(true);
return $this->data['idle'] += $time;
} | php | {
"resource": ""
} |
q266202 | Account.getAmountEstimated | test | public function getAmountEstimated()
{
$accountsVirtual = $this->getAllAccountsVirtual();
$amount = 0.0;
foreach ($accountsVirtual as $account) {
$amount += $account->getAmount();
}
return ($this->getAmount() - $amount);
} | php | {
"resource": ""
} |
q266203 | Route.getRequestMethods | test | public function getRequestMethods(): array
{
if (null === $this->requestMethods) {
$this->requestMethods = [
RequestMethod::GET,
RequestMethod::HEAD,
];
}
return $this->requestMethods;
} | php | {
"resource": ""
} |
q266204 | DisableAutoUpdateHandler.disableWpAutoUpdate | test | protected function disableWpAutoUpdate()
{
$this->wpMockery->addFilter('automatic_updater_disabled', '__return_true');
$this->wpMockery->addFilter('allow_minor_auto_core_updates', '__return_false');
$this->wpMockery->addFilter('allow_major_auto_core_updates', '__return_false');
$this->wpMockery->addFilter('allow_dev_auto_core_updates', '__return_false');
$this->wpMockery->addFilter('auto_update_core', '__return_false');
$this->wpMockery->addFilter('wp_auto_update_core', '__return_false');
$this->wpMockery->addFilter('send_core_update_notification_email', '__return_false');
$this->wpMockery->addFilter('auto_update_translation', '__return_false');
$this->wpMockery->addFilter('auto_core_update_send_email', '__return_false');
$this->wpMockery->addFilter('auto_update_plugin', '__return_false');
$this->wpMockery->addFilter('auto_update_theme', '__return_false');
$this->wpMockery->addFilter('automatic_updates_send_debug_email', '__return_false');
$this->wpMockery->addFilter('automatic_updates_is_vcs_checkout', '__return_true');
$this->wpMockery->addFilter('automatic_updates_send_debug_email ', '__return_false', 1);
if (!defined('AUTOMATIC_UPDATER_DISABLED')) {
define('AUTOMATIC_UPDATER_DISABLED', true);
}
if (!defined('WP_AUTO_UPDATE_CORE')) {
define('WP_AUTO_UPDATE_CORE', false);
}
} | php | {
"resource": ""
} |
q266205 | DisableAutoUpdateHandler.blockWpRequest | test | public function blockWpRequest($pre, $args, $url)
{
if (empty($url)) {
return $pre;
}
/* Invalid host */
if (!$host = $this->wpMockery->parseUrl($url, PHP_URL_HOST)) {
return $pre;
}
$urlData = $this->wpMockery->parseUrl($url);
/* block request */
$path = (false !== stripos($urlData['path'], 'update-check') || false !== stripos($urlData['path'], 'browse-happy'));
if (false !== stripos($host, 'api.wordpress.org') && $path) {
return true;
}
return $pre;
} | php | {
"resource": ""
} |
q266206 | DisableAutoUpdateHandler.hideAdminNag | test | protected function hideAdminNag()
{
if (!function_exists("remove_action")) {
return;
}
/**
* Hide maintenance and update nag
*/
$this->wpMockery->removeAction('admin_notices', 'update_nag', 3);
$this->wpMockery->removeAction('network_admin_notices', 'update_nag', 3);
$this->wpMockery->removeAction('admin_notices', 'maintenance_nag');
$this->wpMockery->removeAction('network_admin_notices', 'maintenance_nag');
$this->wpMockery->removeAction('wp_maybe_auto_update', 'wp_maybe_auto_update');
$this->wpMockery->removeAction('admin_init', 'wp_maybe_auto_update');
$this->wpMockery->removeAction('admin_init', 'wp_auto_update_core');
$this->wpMockery->wpClearScheduledHook('wp_maybe_auto_update');
} | php | {
"resource": ""
} |
q266207 | Quadrilateral.isValidPoint | test | public function isValidPoint(PointInterface $a)
{
return (bool) (
$this->getSegmentAB()->isValidPoint($a) ||
$this->getSegmentBC()->isValidPoint($a) ||
$this->getSegmentCD()->isValidPoint($a) ||
$this->getSegmentDA()->isValidPoint($a)
);
} | php | {
"resource": ""
} |
q266208 | Quadrilateral.isParallelogram | test | public function isParallelogram()
{
$centerdiag1 = $this->getFirstDiagonal();
$centerdiag2 = $this->getSecondDiagonal();
return (bool) Maths::areSamePoint($centerdiag1->getCenter(), $centerdiag2->getCenter());
} | php | {
"resource": ""
} |
q266209 | Descendable.get | test | public function get($composite_key, $default_value = null)
{
$array_keys = explode($this->separator, $composite_key);
$container = $this->container;
foreach ($array_keys as $key) {
if (!$this->hasChild($container, $key)) {
return $default_value;
}
$container = $this->getChild($container, $key);
}
return $container;
} | php | {
"resource": ""
} |
q266210 | Descendable.has | test | public function has($composite_key)
{
$array_keys = explode($this->separator, $composite_key);
$container = $this->container;
foreach ($array_keys as $key) {
if (!$this->hasChild($container, $key)) {
return false;
}
$container = $this->getChild($container, $key);
}
return true;
} | php | {
"resource": ""
} |
q266211 | ApplicationManager.find | test | public function find($id)
{
$application = $this->repository->find($id);
if (null == $application) {
return null;
}
// Load tests
$this->testLoader->loadByApplication($application);
return $application;
} | php | {
"resource": ""
} |
q266212 | ApplicationManager.findAll | test | public function findAll()
{
$applications = array();
foreach ($this->repository->findAll() as $application) {
// Load tests
$this->testLoader->loadByApplication($application);
$applications[] = $application;
}
return $applications;
} | php | {
"resource": ""
} |
q266213 | NumberSystem.equals | test | public function equals(NumberSystem $comparedNumberSystem)
{
if ($this->getBase() !== $comparedNumberSystem->getBase() ||
$this->getSymbolIndex() !== $comparedNumberSystem->getSymbolIndex()
) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q266214 | NumberSystem.getDigits | test | public function getDigits(Number $number)
{
if (null === $this->delimiter) {
return str_split($number->value());
}
return explode($this->delimiter, $number->value());
} | php | {
"resource": ""
} |
q266215 | NumberSystem.buildNumber | test | public function buildNumber(array $digits)
{
$newNumberString = implode($this->delimiter, $digits);
return new Number($newNumberString, $this);
} | php | {
"resource": ""
} |
q266216 | NumberSystem.validateNumberValue | test | public function validateNumberValue($value)
{
if (null === $this->delimiter) {
$parts = str_split($value);
} else {
$parts = explode($this->delimiter, $value);
}
foreach ($parts as $numberSymbol) {
if (!$this->containsSymbol($numberSymbol)) {
throw new NumberParseException($value, $numberSymbol);
}
}
return true;
} | php | {
"resource": ""
} |
q266217 | PHPRedis.makeCall | test | public function makeCall($name, array $arguments = [])
{
if (!$this->connected) {
$this->_connect();
}
// ignore connect commands
if (in_array($name, ['connect', 'pconnect'])) {
return;
}
$log = true;
switch (strtolower($name)) {
case 'open':
case 'popen':
case 'close':
case 'setoption':
case 'getoption':
case 'auth':
case 'select':
$log = false;
break;
}
$ts = microtime(true);
$result = call_user_func_array('parent::'.$name, $arguments);
$ts = (microtime(true) - $ts) * 1000;
$isError = false;
if ($error = $this->getLastError()) {
$this->clearLastError();
$isError = true;
}
if ($log && null !== $this->logger) {
$this->logger->logCommand($this->getCommandString($name, $arguments), $ts, $this->name, $isError);
}
if ($isError) {
throw new PHPRedisCommunicationException('Redis command failed: '.$error);
}
return $result;
} | php | {
"resource": ""
} |
q266218 | PHPRedis.generateKey | test | public function generateKey($kp)
{
$arguments = func_get_args();
if (is_array($arguments[0])) {
$arguments = $arguments[0];
}
return implode(':', $arguments);
} | php | {
"resource": ""
} |
q266219 | PHPRedis._connect | test | private function _connect($bailOnError = false)
{
$this->connected = $this->connect(
$this->parameters['host'],
$this->parameters['port'],
($this->parameters['timeout'] ?: 0)
);
if ($this->connected) {
if ($this->parameters['auth']) {
$this->auth($this->parameters['auth']);
}
if ($this->select($this->parameters['database'])) {
// setup default options
$this->setOption(\Redis::OPT_PREFIX, $this->parameters['prefix']);
$this->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
return true;
}
} elseif (!$bailOnError) {
// try to re-connect, but only once.
usleep(1000);
$this->_connect(true);
}
$error = $this->getLastError();
$this->clearLastError();
if ($this->logger) {
$this->logger->err('Could not connect to redis server (' . $error . ')');
}
throw new PHPRedisCommunicationException('Could not connect to Redis: '.$error);
} | php | {
"resource": ""
} |
q266220 | PHPRedis.getCommandString | test | private function getCommandString($command, array $arguments)
{
$list = [];
foreach ($arguments as $argument) {
$list[] = is_scalar($argument) ? $argument : '[.. complex type ..]';
}
return mb_substr(trim(strtoupper($command) . ' ' . $this->getPrefix() . implode(' ', $list)), 0, 256);
} | php | {
"resource": ""
} |
q266221 | MongoEventStore.getMongoDocument | test | protected function getMongoDocument(DomainEventMessageInterface $domainEventMessage): array
{
$payload = $this
->getSerializer()
->serialize($domainEventMessage->getPayload());
return [
'aggregate_id' => $domainEventMessage->getAggregateId(),
'sequence' => $domainEventMessage->getSequence(),
'occurred_on' => new UTCDateTime(
$domainEventMessage
->getOccurredOn()
->format('Uv')
),
'payload' => [
'name' => $payload->getClassName(),
'data' => (object)$payload->getData(),
],
'meta_data' => (object)$domainEventMessage->getMetaData(),
];
} | php | {
"resource": ""
} |
q266222 | MongoEventStore.getDomainEventMessage | test | protected function getDomainEventMessage(array $document): DomainEventMessageInterface
{
$payload = $this
->getSerializer()
->unserialize(new SerializedObject(
$document['payload']['name'],
$document['payload']['data']
));
/** @var PayloadInterface $payload */
return new DomainEventMessage(
$payload,
new PayloadType($payload),
$document['occurred_on']->toDateTime(),
$document['aggregate_id'],
$document['sequence'],
$document['meta_data']
);
} | php | {
"resource": ""
} |
q266223 | Base.reset | test | public function reset()
{
unset($this->entity);
unset($this->entities);
unset($this->forms);
unset($this->valid);
unset($this->params);
$this->setOperation(self::OPERATION_NONE);
unset($this->formValidators);
$this->errorMessages = array();
$this->useSessionMessage = true;
return $this;
} | php | {
"resource": ""
} |
q266224 | Base.normalizeMessages | test | protected function normalizeMessages($messages)
{
$queue = array();
foreach ($messages as $key => $value) {
if (is_array($value) && count($value)) {
$queue[$key] = (array) array_pop($value);
} else {
$queue[$key] = (array) $value;
}
}
return $queue;
} | php | {
"resource": ""
} |
q266225 | Base.postValidate | test | protected function postValidate($valid, Params $params, $options = array())
{
if ($valid) {
foreach ($this->getEntities() as $tag => $entity) {
$this->em()->persist($entity);
}
if (!isset($options[static::OPTION_NO_FLUSH]) || !$options[static::OPTION_NO_FLUSH]) {
$this->em()->flush();
}
}
} | php | {
"resource": ""
} |
q266226 | Base.formDataEvent | test | protected function formDataEvent($tag, $callable = null)
{
$this->getEventManager()->attach(self::EVENT_FORM_DATA.$tag, function ($event) use ($callable) {
$eventParams = $event->getParams();
/* @var $form \Zend\Form\Form */
$form = $eventParams['form'];
/* @var $data Param */
$data = $eventParams['data'];
if (!empty($callable) && is_callable($callable)) {
$data = call_user_func($callable, $data);
}
$form->setData($data->get());
});
} | php | {
"resource": ""
} |
q266227 | Base.getForms | test | public function getForms()
{
if (!isset($this->forms)) {
$forms = array();
$entities = $this->getEntities();
// set up any connections
$this->beforeFormGeneration($entities);
foreach ($entities as $tag => $entity) {
/* @var $form \Zend\Form\Form */
$form = $this->entityToForm($entity);
$this->getEventManager()
->trigger(self::EVENT_CONFIGURE_FORM.$tag, $this, array(
'tag' => $tag,
'entity' => $entity,
'form' => $form,
'entities' => $entities,
));
$forms[$tag] = $form;
}
$this->forms = $forms;
}
return $this->forms;
} | php | {
"resource": ""
} |
q266228 | Base.removeStringFromArray | test | protected function removeStringFromArray(&$list, $value)
{
$index = array_search($value, $list);
if ($index !== false) {
unset($list[$index]);
}
return $this;
} | php | {
"resource": ""
} |
q266229 | Base.getEntities | test | final public function getEntities()
{
if (!isset($this->entities)) {
$this->entities = array();
$entities = $this->generateEntities();
$entities[static::MAIN_TAG] = $this->getEntity();
/* @var $entity \FzyCommon\Entity\BaseInterface */
foreach ($entities as $tag => $entity) {
$this->getEventManager()
->trigger(self::EVENT_CONFIGURE_ENTITY.$tag, $this, array(
'tag' => $tag,
'entity' => $entity,
'entities' => $entities,
));
$this->entities[$tag] = $entity;
$entity->setFormTag($tag);
}
}
return $this->entities;
} | php | {
"resource": ""
} |
q266230 | Base.swapEntity | test | final public function swapEntity($tag, BaseInterface $entity)
{
if (!isset($this->entities[$tag])) {
throw new \RuntimeException("Unable to swap entity that does not exist");
}
$this->entities[$tag] = $entity;
$entity->setFormTag($tag);
$this->getEventManager()
->trigger(self::EVENT_CONFIGURE_ENTITY.$tag, $this, array(
'tag' => $tag,
'entity' => $entity,
'entities' => $this->getEntities(),
));
return $this;
} | php | {
"resource": ""
} |
q266231 | Base.configureFormToExcludeData | test | public function configureFormToExcludeData($tag, array $elementNames)
{
$removeCallable = array($this, 'removeStringFromArray');
$self = $this;
$this->getEventManager()->attach(self::EVENT_CONFIGURE_FORM.$tag, function (Event $event) use ($elementNames, $self) {
/* @var $form \Zend\Form\Form */
$form = $event->getParam('form');
$fieldsToValidate = array_keys($form->getElements());
foreach ($elementNames as $elementToRemove) {
$self->removeStringFromArray($fieldsToValidate, $elementToRemove);
}
$form->setValidationGroup($fieldsToValidate);
});
} | php | {
"resource": ""
} |
q266232 | Base.setSubFormDataHandler | test | public function setSubFormDataHandler($tag, $paramName)
{
$this->formDataEvent($tag, function (Params $params) use ($paramName) {return Params::create($params->get($paramName));});
return $this;
} | php | {
"resource": ""
} |
q266233 | Base.afterAttach | test | public function afterAttach($formObject, $form, $mainEntity, $tag)
{
foreach ($this->getExcludedFieldsForEntityTag($tag) as $fieldName) {
/* @var \Zend\Form\Form $form */
$form->remove($fieldName);
}
} | php | {
"resource": ""
} |
q266234 | HTTP_Request2_Adapter_Mock.addResponse | test | public function addResponse($response, $url = null)
{
if (is_string($response)) {
$response = self::createResponseFromString($response);
} elseif (is_resource($response)) {
$response = self::createResponseFromFile($response);
} elseif (!$response instanceof HTTP_Request2_Response &&
!$response instanceof Exception
) {
throw new HTTP_Request2_Exception('Parameter is not a valid response');
}
$this->responses[] = array($response, $url);
} | php | {
"resource": ""
} |
q266235 | HTTP_Request2_Adapter_Mock.createResponseFromString | test | public static function createResponseFromString($str)
{
$parts = preg_split('!(\r?\n){2}!m', $str, 2);
$headerLines = explode("\n", $parts[0]);
$response = new HTTP_Request2_Response(array_shift($headerLines));
foreach ($headerLines as $headerLine) {
$response->parseHeaderLine($headerLine);
}
$response->parseHeaderLine('');
if (isset($parts[1])) {
$response->appendBody($parts[1]);
}
return $response;
} | php | {
"resource": ""
} |
q266236 | HTTP_Request2_Adapter_Mock.createResponseFromFile | test | public static function createResponseFromFile($fp)
{
$response = new HTTP_Request2_Response(fgets($fp));
do {
$headerLine = fgets($fp);
$response->parseHeaderLine($headerLine);
} while ('' != trim($headerLine));
while (!feof($fp)) {
$response->appendBody(fread($fp, 8192));
}
return $response;
} | php | {
"resource": ""
} |
q266237 | Versions.makeHeadVersion | test | public function makeHeadVersion($entity) {
if($entity->isHead()) {
return false;
}
$oldHead = $entity->getHead();
// update references on all old versions
$this->entities->createQueryBuilder()
->update($this->entityName, 'o')
->set('o.headVersion', ':newHead')
->where('o.headVersion = :oldHead')
->setParameter('newHead', $entity)
->setParameter('oldHead', $oldHead)
->getQuery()
->execute();
// make the old head now just a sub-version
$oldHead->setHead($entity);
$this->persist($oldHead, false);
// make this entity the head
$entity->setHead(null);
$this->persist($entity, false);
$this->entities->flush();
return true;
} | php | {
"resource": ""
} |
q266238 | Versions.needsNewVersion | test | protected function needsNewVersion($entity) {
if(!$entity->isHead()) {
return false;
}
if(!$entity->hasVersions()) {
return true;
}
$oldTimestamp = $entity->getVersions()->first()->getUpdatedAt();
$newTimestamp = Carbon::now();
$diff = $newTimestamp->diffInHours($oldTimestamp);
if($diff >= 24) {
return true;
}
} | php | {
"resource": ""
} |
q266239 | Versions.persist | test | public function persist($entity, $version = 'guess') {
$this->entities->persist($entity);
if($version === 'new' || ($version === 'guess' && $this->needsNewVersion($entity))) {
$this->makeNewVersion($entity, false);
$return = true;
} else {
$return = false;
}
$this->entities->flush();
return $return;
} | php | {
"resource": ""
} |
q266240 | Versions.clearVersions | test | public function clearVersions($entity) {
$entity = $entity->getHead();
$versions = $entity->getVersions();
foreach($versions as $version) {
$this->delete($version, false);
}
$versions->clear();
$this->persist($entity, 'overwrite');
return $entity;
} | php | {
"resource": ""
} |
q266241 | Uploader.cleanUp | test | private function cleanUp($path)
{
$fs = $this->getFilesystem();
$parts = explode('/', $path);
while (0 < count($parts)) {
$key = implode('/', $parts);
if ($fs->has($key)) {
$dir = $fs->get($key);
if (!$dir->isDir() || 0 < count($fs->listContents($key))) {
break;
}
if (!$fs->deleteDir($key)) {
throw new UploadException(sprintf('Failed to delete directory "%s".', $key));
}
}
array_pop($parts);
}
} | php | {
"resource": ""
} |
q266242 | Uploader.checkKey | test | private function checkKey($sourceKey)
{
if ($this->mountManager->has($sourceKey)) {
return true;
}
if ($this->reconnectDistantFs($sourceKey)) {
if ($this->mountManager->has($sourceKey)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q266243 | Uploader.moveKey | test | private function moveKey($sourceKey, $targetKey)
{
if (!$this->isDistant($sourceKey)) {
return $this->mountManager->move($sourceKey, $targetKey);
}
if ($this->mountManager->copy($sourceKey, $targetKey)) {
return true;
}
if ($this->reconnectDistantFs($sourceKey)) {
if ($this->mountManager->copy($sourceKey, $targetKey)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q266244 | Uploader.reconnectDistantFs | test | private function reconnectDistantFs($key)
{
/** @noinspection PhpUnusedLocalVariableInspection */
list($prefix, $args) = $this->mountManager->filterPrefix([$key]);
/** @var \League\Flysystem\FileSystem $fs */
$fs = $this->mountManager->getFilesystem($prefix);
$adapter = $fs->getAdapter();
// Try reconnection
if (!$adapter instanceof AbstractFtpAdapter) {
return false;
}
$adapter->disconnect();
sleep(1);
$adapter->connect();
return true;
} | php | {
"resource": ""
} |
q266245 | Uploader.isDistant | test | private function isDistant($key)
{
/** @noinspection PhpUnusedLocalVariableInspection */
list($prefix, $args) = $this->mountManager->filterPrefix([$key]);
/** @var \League\Flysystem\FileSystem $fs */
$fs = $this->mountManager->getFilesystem($prefix);
$adapter = $fs->getAdapter();
// Try reconnection
if ($adapter instanceof AbstractFtpAdapter) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q266246 | OwpDkim.createPath | test | static private function createPath($path)
{
if (is_dir($path)) return true;
$prev_path = substr($path, 0, (strrpos($path, '/', -2) + 1));
$return = self::createPath($prev_path);
return ($return && is_writable($prev_path)) ? mkdir($path) : false;
} | php | {
"resource": ""
} |
q266247 | PDORepository.find | test | public function find($id, bool $getRelations = null): ? Entity
{
if (! \is_string($id) && ! \is_int($id)) {
throw new InvalidArgumentException('ID should be an int or string only.');
}
return $this->findBy(
[$this->entity::getIdField() => $id],
null,
null,
null,
null,
$getRelations
)[0]
?? null;
} | php | {
"resource": ""
} |
q266248 | PDORepository.create | test | public function create(Entity $entity): bool
{
$this->validateEntity($entity);
return $this->saveCreateDelete('insert', $entity);
} | php | {
"resource": ""
} |
q266249 | PDORepository.save | test | public function save(Entity $entity): bool
{
$this->validateEntity($entity);
return $this->saveCreateDelete('update', $entity);
} | php | {
"resource": ""
} |
q266250 | PDORepository.delete | test | public function delete(Entity $entity): bool
{
$this->validateEntity($entity);
return $this->saveCreateDelete('delete', $entity);
} | php | {
"resource": ""
} |
q266251 | PDORepository.validateEntity | test | protected function validateEntity(Entity $entity): void
{
if (! ($entity instanceof $this->entity)) {
throw new InvalidEntityException(
'This repository expects entities to be instances of '
. $this->entity
. '. Entity instanced from '
. \get_class($entity)
. ' provided instead.'
);
}
} | php | {
"resource": ""
} |
q266252 | PDORepository.select | test | protected function select(
array $columns = null,
array $criteria = null,
array $orderBy = null,
int $limit = null,
int $offset = null,
bool $getRelations = null
) {
// Build the query
$query = $this->selectQueryBuilder($columns, $criteria, $orderBy, $limit, $offset);
// Create a new PDO statement from the query builder
$stmt = $this->store->prepare($query->getQuery());
// Iterate through the criteria once more
foreach ($criteria as $column => $criterion) {
// If the criterion is null
if ($criterion === null) {
// Skip as we've already set the where to IS NULL
continue;
}
// If the criterion is an array
if (\is_array($criterion)) {
// Iterate through the criterion and bind each value individually
foreach ($criterion as $index => $criterionItem) {
$stmt->bindValue($this->columnParam($column . $index), $criterionItem);
}
continue;
}
// And bind each value to the column
$stmt->bindValue($this->columnParam($column), $criterion);
}
// Execute the PDO statement
$stmt->execute();
// Get all the results from the PDO statement
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$results = [];
// If the result of the query was a count
if (isset($rows[0]['COUNT(*)'])) {
return (int) $rows[0]['COUNT(*)'];
}
// Iterate through the rows found
foreach ($rows as $row) {
// Create a new model
/** @var \Valkyrja\ORM\Entity $entity */
$entity = new $this->entity();
// Apply the model's contents given the row
$entity->fromArray($row);
// If no columns were specified then we can safely get all the relations
if (null === $columns && $getRelations === true) {
// Add the model to the final results
$results[] = $this->getEntityRelations($entity);
} else {
// Add the model to the final results
$results[] = $entity;
}
}
return $results;
} | php | {
"resource": ""
} |
q266253 | PDORepository.selectQueryBuilder | test | protected function selectQueryBuilder(
array $columns = null,
array $criteria = null,
array $orderBy = null,
int $limit = null,
int $offset = null
): QueryBuilder {
// Create a new query
$query = $this->entityManager
->getQueryBuilder()
->select($columns)
->table($this->table);
// If criteria has been passed
if (null !== $criteria) {
$this->setCriteriaInQuery($query, $criteria);
}
// If order by has been passed
if (null !== $orderBy) {
$this->setOrderByInQuery($query, $orderBy);
}
// If a limit is passed
if (null !== $limit) {
$this->setLimitInQuery($query, $limit);
}
// If an offset is passed
if (null !== $offset) {
$this->setOffsetInQuery($query, $offset);
}
return $query;
} | php | {
"resource": ""
} |
q266254 | PDORepository.setCriteriaInQuery | test | protected function setCriteriaInQuery(QueryBuilder $query, array $criteria): void
{
// Iterate through each criteria and set the column = :column
// so we can use bindColumn() in PDO later
foreach ($criteria as $column => $criterion) {
// If the criterion is null
if ($criterion === null) {
$this->setNullCriterionInQuery($query, $column);
continue;
}
// If the criterion is an array
if (\is_array($criterion)) {
$this->setArrayCriterionInQuery($query, $column, $criterion);
continue;
}
// If the criterion has a percent at the start or the end
if ($criterion[0] === '%' || $criterion[\strlen($criterion) - 1] === '%') {
$this->setLikeCriterionInQuery($query, $column);
continue;
}
$this->setEqualCriterionInQuery($query, $column);
}
} | php | {
"resource": ""
} |
q266255 | PDORepository.setArrayCriterionInQuery | test | protected function setArrayCriterionInQuery(QueryBuilder $query, string $column, array $criterion): void
{
$criterionConcat = '';
$lastIndex = \count($criterion) - 1;
// Iterate through the criterion and set each item individually to be bound later
foreach ($criterion as $index => $criterionItem) {
$criterionConcat .= $this->columnParam($column . $index);
// If this is not the last index, add a comma
if ($index < $lastIndex) {
$criterionConcat .= ',';
}
}
// Set the where statement as an in
$query->where($column . ' IN (' . $criterionConcat . ')');
} | php | {
"resource": ""
} |
q266256 | PDORepository.setOrderByInQuery | test | protected function setOrderByInQuery(QueryBuilder $query, array $orderBy): void
{
// Iterate through each order by
foreach ($orderBy as $column => $order) {
// Switch through the order (value) set
switch ($order) {
// If the order is ascending
case OrderBy::ASC:
// Set the column via the orderByAsc method
$query->orderByAsc($column);
break;
// If the order is descending
case OrderBy::DESC:
// Set the column via the orderByDesc method
$query->orderByDesc($column);
break;
default:
// Otherwise set the order (which is the column)
$query->orderBy($order);
break;
}
}
} | php | {
"resource": ""
} |
q266257 | PDORepository.saveCreateDelete | test | protected function saveCreateDelete(string $type, Entity $entity): int
{
if (! $this->store->inTransaction()) {
$this->store->beginTransaction();
}
// Create a new query
$query = $this->entityManager
->getQueryBuilder()
->table($this->table)
->{$type}();
$idField = $entity::getIdField();
$properties = $entity->forDataStore();
/* @var QueryBuilder $query */
// If this is an insert
if ($type === 'insert') {
// Ensure all the required properties are set
$this->ensureRequiredProperties($entity, $properties);
}
// If this type isn't an insert
if ($type !== 'insert') {
// Set the id for the where clause
$query->where($idField . ' = ' . $this->criterionParam($idField));
}
if ($type !== 'delete') {
// Set the properties
$this->setPropertiesForSaveCreateDeleteQuery($query, $properties);
}
// Prepare a PDO statement with the query
$stmt = $this->store->prepare($query->getQuery());
// If this type isn't an insert
if ($type !== 'insert') {
// Set the id value for the where clause
$stmt->bindValue($this->criterionParam($idField), $properties[$idField]);
}
if ($type !== 'delete') {
// Set the properties.
$this->setPropertiesForSaveCreateDeleteStatement($stmt, $properties);
}
// If the execute failed
if (! $executeResult = $stmt->execute()) {
// Throw a fail exception
throw new ExecuteException($stmt->errorInfo()[2]);
}
return $executeResult;
} | php | {
"resource": ""
} |
q266258 | PDORepository.setPropertiesForSaveCreateDeleteQuery | test | protected function setPropertiesForSaveCreateDeleteQuery(QueryBuilder $query, array $properties): void
{
// Iterate through the properties
foreach ($properties as $column => $property) {
if ($property === null) {
continue;
}
// Set the column and param name
$query->set($column, $this->columnParam($column));
}
} | php | {
"resource": ""
} |
q266259 | PDORepository.setPropertiesForSaveCreateDeleteStatement | test | protected function setPropertiesForSaveCreateDeleteStatement(PDOStatement $statement, array $properties): void
{
// Iterate through the properties
foreach ($properties as $column => $property) {
if ($property === null) {
continue;
}
// If the property is an object, then serialize it
if (\is_object($property)) {
$property = \serialize($property);
} // Otherwise json encode if its an array
elseif (\is_array($property)) {
$property = \json_encode($property);
}
$type = PDO::PARAM_STR;
if (\is_int($property) || \is_bool($property)) {
$type = PDO::PARAM_INT;
$property = (int) $property;
}
// Bind each column's value to the statement
$statement->bindValue($this->columnParam($column), $property, $type);
}
} | php | {
"resource": ""
} |
q266260 | PDORepository.getEntityRelations | test | protected function getEntityRelations(Entity $entity): Entity
{
$propertyTypes = $entity::getPropertyTypes();
$propertyMapper = $entity->getPropertyMapper();
// Iterate through the property types
foreach ($propertyTypes as $property => $type) {
$entityName = \is_array($type) ? $type[0] : $type;
$propertyMap = $propertyMapper[$property] ?? null;
if (null !== $propertyMap && (\is_array($type) || ! PropertyType::isValid($type))) {
$repository = $this->entityManager->getRepository($entityName);
$orderBy = $propertyMap[PropertyMap::ORDER_BY] ?? null;
$limit = $propertyMap[PropertyMap::LIMIT] ?? null;
$offset = $propertyMap[PropertyMap::OFFSET] ?? null;
$columns = $propertyMap[PropertyMap::COLUMNS] ?? null;
$getRelations = $propertyMap[PropertyMap::GET_RELATIONS] ?? true;
unset(
$propertyMap[PropertyMap::ORDER_BY],
$propertyMap[PropertyMap::LIMIT],
$propertyMap[PropertyMap::OFFSET],
$propertyMap[PropertyMap::COLUMNS],
$propertyMap[PropertyMap::GET_RELATIONS]
);
$entities = $repository->findBy($propertyMap, $orderBy, $limit, $offset, $columns, $getRelations);
if (\is_array($type)) {
$entity->{$property} = $entities;
continue;
}
if (empty($entities)) {
continue;
}
$entity->{$property} = $entities[0];
}
}
return $entity;
} | php | {
"resource": ""
} |
q266261 | PDORepository.ensureRequiredProperties | test | protected function ensureRequiredProperties(Entity $entity, array $properties): void
{
// Iterate through the required properties
foreach ($entity::getRequiredProperties() as $requiredProperty) {
// If the required property is not set
if (! isset($properties[$requiredProperty])) {
// Throw an exception
throw new InvalidArgumentException('Missing required property: ' . $requiredProperty);
}
}
} | php | {
"resource": ""
} |
q266262 | Steemit.broadcast | test | private function broadcast($body)
{
$method = 'POST';
$url = "{$this->domain}/broadcast";
$headears = $this->getHeaders();
$body = json_encode($body);
try {
$request = $this->getClient()->request($method, $url, [
'headers' => $headears,
'body' => $body
]);
$response = $request->getBody()->getContents();
return json_decode($response, true);
} catch (RequestException $e) {
$response = $e->getResponse()->getBody()->getContents();
$response = json_decode($response, true);
return $response;
} catch (\Exception $e) {
return ['error' => $e->getCode(), 'error_description' => $e->getMessage()];
}
} | php | {
"resource": ""
} |
q266263 | Steemit.exec | test | public function exec($do, array $params)
{
$body = call_user_func_array(array($this->operations, $do), $params);
return $this->broadcast($body);
} | php | {
"resource": ""
} |
q266264 | NoCaptcha.getScriptSrc | test | private function getScriptSrc($callbackName = null)
{
$queries = [];
if ($this->hasLang()) {
array_set($queries, 'hl', $this->lang);
}
if ($this->hasCallbackName($callbackName)) {
array_set($queries, 'onload', $callbackName);
array_set($queries, 'render', 'explicit');
}
return static::CLIENT_URL . (count($queries) ? '?' . http_build_query($queries) : '');
} | php | {
"resource": ""
} |
q266265 | NoCaptcha.display | test | public function display($name = null, array $attributes = [])
{
$output = $this->attributes->build($this->siteKey, array_merge(
$this->attributes->prepareNameAttribute($name),
$attributes
));
return '<div ' . $output . '></div>';
} | php | {
"resource": ""
} |
q266266 | NoCaptcha.image | test | public function image($name = null, array $attributes = [])
{
return $this->display(
$name, array_merge($attributes, $this->attributes->getImageAttribute())
);
} | php | {
"resource": ""
} |
q266267 | NoCaptcha.audio | test | public function audio($name = null, array $attributes = [])
{
return $this->display(
$name, array_merge($attributes, $this->attributes->getAudioAttribute())
);
} | php | {
"resource": ""
} |
q266268 | NoCaptcha.verify | test | public function verify($response, $clientIp = null)
{
if (empty($response)) return false;
$response = $this->sendVerifyRequest([
'secret' => $this->secret,
'response' => $response,
'remoteip' => $clientIp
]);
return isset($response['success']) && $response['success'] === true;
} | php | {
"resource": ""
} |
q266269 | NoCaptcha.verifyRequest | test | public function verifyRequest(ServerRequestInterface $request)
{
$body = $request->getParsedBody();
$server = $request->getServerParams();
$response = isset($body[self::CAPTCHA_NAME])
? $body[self::CAPTCHA_NAME]
: '';
$remoteIp = isset($server['REMOTE_ADDR'])
? $server['REMOTE_ADDR']
: null;
return $this->verify($response, $remoteIp);
} | php | {
"resource": ""
} |
q266270 | NoCaptcha.script | test | public function script($callbackName = null)
{
$script = '';
if ( ! $this->scriptLoaded) {
$script = '<script src="' . $this->getScriptSrc($callbackName) . '" async defer></script>';
$this->scriptLoaded = true;
}
return $script;
} | php | {
"resource": ""
} |
q266271 | NoCaptcha.scriptWithCallback | test | public function scriptWithCallback(array $captchas, $callbackName = 'captchaRenderCallback')
{
$script = $this->script($callbackName);
if (empty($script) || empty($captchas)) {
return $script;
}
return implode(PHP_EOL, [implode(PHP_EOL, [
'<script>',
"
var ".implode(',', $captchas).";
var $callbackName = function() {",
$this->renderCaptchas($captchas),
'};',
'</script>'
]), $script]);
} | php | {
"resource": ""
} |
q266272 | NoCaptcha.checkKey | test | private function checkKey($name, &$value)
{
$this->checkIsString($name, $value);
$value = trim($value);
$this->checkIsNotEmpty($name, $value);
} | php | {
"resource": ""
} |
q266273 | NoCaptcha.checkIsString | test | private function checkIsString($name, $value)
{
if ( ! is_string($value)) {
throw new Exceptions\ApiException(
'The ' . $name . ' must be a string value, ' . gettype($value) . ' given'
);
}
} | php | {
"resource": ""
} |
q266274 | NoCaptcha.sendVerifyRequest | test | private function sendVerifyRequest(array $query = [])
{
$query = array_filter($query);
$url = static::VERIFY_URL . '?' . http_build_query($query);
$response = $this->request->send($url);
return $response;
} | php | {
"resource": ""
} |
q266275 | View.init | test | public function init()
{
parent::init();
if (is_array($this->theme)) {
if (!isset($this->theme['class'])) {
$this->theme['class'] = 'Reaction\Base\Theme';
}
$this->theme = \Reaction::create($this->theme);
} elseif (is_string($this->theme)) {
$this->theme = \Reaction::create($this->theme);
}
} | php | {
"resource": ""
} |
q266276 | View.findViewFile | test | public function findViewFile($view, $context = null)
{
if (strncmp($view, '@', 1) === 0) {
// e.g. "@app/views/main"
$file = \Reaction::$app->getAlias($view);
} elseif (strncmp($view, '//', 2) === 0) {
// e.g. "//layouts/main"
$file = Reaction::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
} elseif ($context instanceof ViewContextInterface) {
$view = ltrim($view, '/');
$file = $context->getViewPath() . DIRECTORY_SEPARATOR . $view;
} elseif (($currentViewFile = $this->getViewFile()) !== false) {
$file = dirname($currentViewFile) . DIRECTORY_SEPARATOR . $view;
} else {
throw new InvalidCallException("Unable to resolve view file for view '$view': no active view context.");
}
$pathInfo = pathinfo($file, PATHINFO_EXTENSION);
if ($pathInfo !== '' && !empty($pathInfo)) {
return $file;
}
$path = $file . '.' . $this->defaultExtension;
if ($this->defaultExtension !== 'php' && !is_file($path)) {
$path = $file . '.php';
}
return $path;
} | php | {
"resource": ""
} |
q266277 | View.renderPhpStateless | test | public static function renderPhpStateless($_file_, $_params_ = [])
{
$_file_ = Reaction::$app->getAlias($_file_);
$_obInitialLevel_ = ob_get_level();
ob_start();
ob_implicit_flush(false);
extract($_params_, EXTR_OVERWRITE);
try {
require $_file_;
return ob_get_clean();
} catch (\Exception $e) {
while (ob_get_level() > $_obInitialLevel_) {
if (!@ob_end_clean()) {
ob_clean();
}
}
throw $e;
} catch (\Throwable $e) {
while (ob_get_level() > $_obInitialLevel_) {
if (!@ob_end_clean()) {
ob_clean();
}
}
throw $e;
}
} | php | {
"resource": ""
} |
q266278 | Helper.registerPostTypes | test | public function registerPostTypes()
{
if (!function_exists('register_post_type')) {
return;
}
$this->postTypes->rewind();
while ($this->postTypes->valid()) {
$postType = $this->postTypes->current();
register_post_type($postType->getName(), $postType->getArgs());
$this->postTypes->next();
}
} | php | {
"resource": ""
} |
q266279 | TokenFactory.generateToken | test | public function generateToken($token, KeyPairReference $keyPair = null)
{
return new Token($token, $this->prepareKeyPair($keyPair));
} | php | {
"resource": ""
} |
q266280 | TokenFactory.generateMemoryToken | test | public function generateMemoryToken($token, KeyPairReference $keyPair = null)
{
return new MemoryToken($token, $this->prepareKeyPair($keyPair));
} | php | {
"resource": ""
} |
q266281 | ExecutePrototypeInstaller.execute | test | public function execute(string $projectFolder) {
$shell = $this->getShell()->setDirectory(implode(DIRECTORY_SEPARATOR, [rtrim($this->getBaseFolder(), '\/'), ltrim($projectFolder, '\/')]));
$shell->run($this->getCommandBuilder()->reset()->addParam('prototype'));
$shell->run($this->getCommandBuilder()->reset()->addParam('update'));
} | php | {
"resource": ""
} |
q266282 | TwigExtension.messageFilterCallback | test | public function messageFilterCallback( $key /*...*/ ) {
$params = func_get_args();
array_shift( $params );
if ( count( $params ) == 1 && is_array( $params[0] ) ) {
// Unwrap args array
$params = $params[0];
}
$msg = $this->ctx->message( $key, $params );
return $msg->plain();
} | php | {
"resource": ""
} |
q266283 | StdioLogger.notice | test | public function notice($message, array $context = array(), $traceShift = 0)
{
$this->log(LogLevel::NOTICE, $message, $context, $traceShift);
} | php | {
"resource": ""
} |
q266284 | StdioLogger.info | test | public function info($message, array $context = array(), $traceShift = 0)
{
$this->log(LogLevel::INFO, $message, $context, $traceShift);
} | php | {
"resource": ""
} |
q266285 | StdioLogger.debug | test | public function debug($message, array $context = array(), $traceShift = 0)
{
$this->log(LogLevel::DEBUG, $message, $context, $traceShift);
} | php | {
"resource": ""
} |
q266286 | StdioLogger.logRaw | test | public function logRaw($message, array $context = array(), $traceShift = 0)
{
$this->log(static::LOG_LEVEL_RAW, $message, $context, $traceShift);
} | php | {
"resource": ""
} |
q266287 | StdioLogger.profileEnd | test | public function profileEnd($endId, $message = null, $traceShift = null)
{
if (!isset($endId)) {
return;
}
$this->profile($message, $endId, $traceShift);
} | php | {
"resource": ""
} |
q266288 | StdioLogger.log | test | public function log($level, $message, array $context = [], $traceShift = 0)
{
$this->checkCorrectLogLevel($level);
$message = $this->convertMessageToString($message);
$message = $this->processPlaceHolders($message, $context);
if (strlen($message) > 0 && mb_substr($message, -1) !== "\n" && !$this->newLine) {
$message .= self::NEW_LINE;
}
if ($this->hideLevel === false) {
$logColors = isset(static::$LOG_COLORS[$level]) ? static::$LOG_COLORS[$level] : [];
if ($level !== static::LOG_LEVEL_RAW) {
$message = str_pad('[' . $level . ']', 10, ' ') . $message;
}
if (!empty($logColors)) {
$message = $this->colorizeText($message, $logColors);
}
}
if ($this->newLine === true) {
$message .= self::NEW_LINE;
}
//Add script and line number
if ($this->withLineNum) {
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$lineNum = $this->getCalleeData($trace, $traceShift + 1);
$unixTime = microtime(true);
$micro = substr(sprintf("%06d", ($unixTime - floor($unixTime)) * 1000000), 0, 3);
$time = date('H:i:s') . '.' . $micro;
$message .= $this->colorizeText('^^^ ' . $time . ' - ' . $lineNum, static::FG_BLACK) . self::NEW_LINE;
}
$message = $this->format($message, $context);
$this->stdio->write($message);
} | php | {
"resource": ""
} |
q266289 | StdioLogger.convertMessageToString | test | protected function convertMessageToString($message) {
$messageStr = $message;
if ($message === null) {
$messageStr = 'NULL';
} elseif ($message instanceof \Throwable) {
$messageStr = $this->convertErrorToString($message);
} elseif (is_bool($message)) {
$messageStr = $message ? 'TRUE' : 'FALSE';
} elseif (!is_scalar($message)) {
$messageStr = print_r($message, true);
}
return $messageStr;
} | php | {
"resource": ""
} |
q266290 | StdioLogger.convertErrorToString | test | protected function convertErrorToString(\Throwable $e, $withTrace = true) {
$message = [
$e->getMessage(),
!empty($e->getFile()) ? $e->getFile() . ' #' . $e->getLine() : "",
$e->getTraceAsString(),
];
if ($withTrace) {
$message[] = $e->getTraceAsString();
if ($e->getPrevious() !== null) {
$message[] = $this->convertErrorToString($e->getPrevious(), false);
}
}
return implode("\n", $message);
} | php | {
"resource": ""
} |
q266291 | StdioLogger.colorizeText | test | protected function colorizeText($text, ...$colors) {
if (is_array($colors[0])) {
$colors = $colors[0];
}
for ($i = 0; $i < count($colors); $i++) {
$text = $this->_colorizeTextInternal($text, $colors[$i]);
}
return $text;
} | php | {
"resource": ""
} |
q266292 | StdioLogger.getCalleeData | test | private function getCalleeData($trace, $pos = 0) {
$traceRow = isset($trace[$pos]) ? $trace[$pos] : end($trace);
$file = isset($traceRow['file']) ? $traceRow['file'] : '[internal function]';
$line = isset($traceRow['line']) ? '#' . $traceRow['line'] : '';
$str = $file . " " . $line;
return $str;
} | php | {
"resource": ""
} |
q266293 | StdioLogger.processPlaceHolders | test | protected function processPlaceHolders(string $message, array $context): string
{
if (false === strpos($message, '{')) {
return $message;
}
$replacements = [];
foreach ($context as $key => $value) {
$replacements['{' . $key . '}'] = $this->formatValue($value);
}
return strtr($message, $replacements);
} | php | {
"resource": ""
} |
q266294 | StdioLogger.formatValue | test | protected function formatValue($value): string
{
if (is_null($value) || is_scalar($value) || (is_object($value) && method_exists($value, '__toString'))) {
return (string)$value;
}
if (is_object($value)) {
return '[object ' . get_class($value) . ']';
}
return '[' . gettype($value) . ']';
} | php | {
"resource": ""
} |
q266295 | Seo.find | test | public static function find(ActiveRecord $owner, $condition = 0)
{
$seo = new self();
$seo->_owner = $owner;
$condition = (int)$condition;
$data = $owner->getIsNewRecord() ? false : (new Query())
->from(Seo::tableName($owner))
->limit(1)
->andWhere([
'condition' => $condition,
'model_id' => $owner->getPrimaryKey(),
])->one($owner->getDb());
$seo->_isNewRecord = empty($data);
if ($data) {
$seo->setAttributes($data);
}
$seo->condition = $condition;
return $seo;
} | php | {
"resource": ""
} |
q266296 | Seo.tableName | test | public static function tableName(ActiveRecord $activeRecord)
{
$tableName = $activeRecord->tableName();
if (substr($tableName, -2) == '}}') {
return preg_replace('/{{(.+)}}/', '{{$1_' . self::$tableSuffix . '}}', $tableName);
} else {
return $tableName . '_' . self::$tableSuffix;
}
} | php | {
"resource": ""
} |
q266297 | Seo.deleteAll | test | public static function deleteAll(ActiveRecord $owner)
{
$owner->getDb()->createCommand()->delete(self::tableName($owner), ['model_id' => $owner->getPrimaryKey()])->execute();
} | php | {
"resource": ""
} |
q266298 | Seo.save | test | public function save()
{
if (empty($this->_owner)) {
$this->addError('owner', "You can't use Seo model without owner");
return false;
}
$this->model_id = $this->_owner->getPrimaryKey();
$command = $this->_owner->getDb()->createCommand();
$attributes = ['title', 'keywords', 'description'];
$tableName = self::tableName($this->_owner);
if ($this->_isNewRecord) {
if (empty(array_filter($this->getAttributes($attributes)))) {
// don't save new SEO data with empty values
return true;
}
$command->insert($tableName, $this->toArray());
} else {
$command->update(
$tableName, $this->toArray($attributes),
['model_id' => $this->model_id, 'condition' => $this->condition]
);
}
$command->execute();
$this->_isNewRecord = false;
return true;
} | php | {
"resource": ""
} |
q266299 | DB.init | test | static function init(){
global $databaseConfig;
if (!isset($databaseConfig)) {
$databaseConfig = array (
'server' => SS_DATABASE_SERVER,
'username' => SS_DATABASE_USERNAME,
'password' => SS_DATABASE_PASSWORD,
'database' => SS_DATABASE_NAME,
);
}
self::$conn = new mysqli($databaseConfig['server'], $databaseConfig['username'], $databaseConfig['password'], $databaseConfig['database']);
self::$conn->query("set sql_mode='ansi'");
} | php | {
"resource": ""
} |
Subsets and Splits