_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q259200 | Form.getField | test | public function getField($key)
{
foreach ($this->fields as $field) {
if ($field->getKey() == $key) {
return $field;
}
}
} | php | {
"resource": ""
} |
q259201 | Form.getFieldsNotInArray | test | public function getFieldsNotInArray($keys)
{
$fields = [];
foreach ($this->fields as $field) {
if (!in_array($field->getKey(), $keys)) {
$fields[] = $field;
}
}
return $fields;
} | php | {
"resource": ""
} |
q259202 | Form.serializeForLocale | test | public function serializeForLocale($locale, Dynamic $dynamic = null)
{
$fields = [];
foreach ($this->fields as $field) {
$fieldTranslation = $field->getTranslation($locale, false, true);
$value = null;
if ($dynamic) {
$value = $dynamic->{$field->getKey()};
}
$fields[$field->getOrder()] = [
'key' => $field->getKey(),
'type' => $field->getType(),
'title' => $fieldTranslation->getTitle(),
'options' => $fieldTranslation->getOptions(),
'defaultValue' => $fieldTranslation->getDefaultValue(),
'placeholder' => $fieldTranslation->getPlaceholder(),
'shortTitle' => $fieldTranslation->getShortTitle(),
'value' => $value,
];
ksort($fields);
}
$translation = $this->getTranslation($locale, false, true);
return [
'id' => $dynamic ? $dynamic->getId() : null,
'formId' => $this->getId(),
'title' => $translation->getTitle(),
'subject' => $translation->getSubject(),
'mailText' => $translation->getMailText(),
'submitLabel' => $translation->getSubmitLabel(),
'successText' => $translation->getSuccessText(),
'fromEmail' => $translation->getFromEmail(),
'fromName' => $translation->getFromName(),
'toEmail' => $translation->getToEmail(),
'toName' => $translation->getToName(),
'fields' => $fields,
'created' => $dynamic ? $dynamic->getCreated() : null,
];
} | php | {
"resource": ""
} |
q259203 | FormWebsiteController.formAction | test | public function formAction(StructureInterface $structure, $preview = false, $partial = false)
{
/** @var Request $request */
$request = $this->get('request_stack')->getCurrentRequest();
// get attributes
$attributes = $this->getAttributes([], $structure, $preview);
$template = $structure->getKey();
$typeClass = $this->getTypeClass($template);
/** @var AbstractType $type */
$type = $this->get('form.registry')->getType($typeClass)->getInnerType();
$type->setAttributes($attributes);
$this->form = $this->get('form.factory')->create($typeClass);
$this->form->handleRequest($request);
if ($this->form->isSubmitted()
&& $this->form->isValid()
&& $response = $this->handleFormSubmit($request, $type, $attributes)
) {
// success form submit
return $response;
}
return parent::indexAction($structure, $preview, $partial);
} | php | {
"resource": ""
} |
q259204 | FormWebsiteController.onlyAction | test | public function onlyAction(Request $request, $key)
{
$ajaxTemplates = $this->container->getParameter('sulu_form.ajax_templates');
if (!$ajaxTemplates[$key]) {
throw new NotFoundHttpException();
}
$typeClass = $this->getTypeClass($key);
/** @var AbstractType $type */
$type = $this->get('form.registry')->getType($typeClass)->getInnerType();
$this->form = $this->get('form.factory')->create($typeClass);
$this->form->handleRequest($request);
if ($this->form->isSubmitted()
&& $this->form->isValid()
&& $response = $this->handleFormOnlySubmit($request, $type)
) {
// success form submit
return $response;
}
return $this->render($ajaxTemplates[$key], ['form' => $this->form->createView()]);
} | php | {
"resource": ""
} |
q259205 | FormWebsiteController.handleFormSubmit | test | private function handleFormSubmit(Request $request, $type, $attributes)
{
// handle form submit
$configuration = $this->get('sulu_form.configuration.form_configuration_factory')->buildByType(
$type,
$this->form->getData(),
$request->getLocale(),
$attributes
);
$success = $this->get('sulu_form.handler')->handle($this->form, $configuration);
if ($success) {
if ($request->isXmlHttpRequest()) {
return new JsonResponse(['send' => $success]);
}
return new RedirectResponse('?send=true');
}
if ($request->isXmlHttpRequest()) {
return new JsonResponse(
[
'send' => false,
'errors' => $this->getErrors(),
],
400
);
}
} | php | {
"resource": ""
} |
q259206 | FormWebsiteController.handleFormOnlySubmit | test | private function handleFormOnlySubmit(Request $request, $type)
{
// handle form submit
$configuration = $this->get('sulu_form.configuration.form_configuration_factory')->buildByType(
$type,
$this->form->getData(),
$request->getLocale(),
[]
);
if ($this->get('sulu_form.handler')->handle($this->form, $configuration)) {
return new RedirectResponse('?send=true');
}
} | php | {
"resource": ""
} |
q259207 | FormWebsiteController.tokenAction | test | public function tokenAction(Request $request)
{
$formName = $request->get('form');
$csrfToken = $this->get('security.csrf.token_manager')->getToken(
$request->get('form')
)->getValue();
$content = $csrfToken;
// this should be the default behaviour in future because for varnish its needed
if ($request->get('html')) {
$content = sprintf(
'<input type="hidden" id="%s__token" name="%s[_token]" value="%s" />',
$formName,
$formName,
$csrfToken
);
}
$response = new Response($content);
/* Deactivate Cache for this token action */
$response->setSharedMaxAge(0);
$response->setMaxAge(0);
// set shared will set the request to public so it need to be done after shared max set to 0
$response->setPrivate();
$response->headers->addCacheControlDirective('no-cache', true);
$response->headers->addCacheControlDirective('must-revalidate', true);
$response->headers->addCacheControlDirective('no-store', true);
return $response;
} | php | {
"resource": ""
} |
q259208 | FormWebsiteController.getErrors | test | protected function getErrors()
{
$errors = [];
$generalErrors = [];
foreach ($this->form->getErrors() as $error) {
$generalErrors[] = $error->getMessage();
}
if (!empty($generalErrors)) {
$errors['general'] = $generalErrors;
}
foreach ($this->form->all() as $field) {
$fieldErrors = [];
foreach ($field->getErrors() as $error) {
$fieldErrors[] = $error->getMessage();
}
if (!empty($fieldErrors)) {
$errors[$field->getName()] = $fieldErrors;
}
}
return $errors;
} | php | {
"resource": ""
} |
q259209 | Handler.handle | test | public function handle(FormInterface $form, FormConfigurationInterface $configuration)
{
if (!$form->isValid()) {
return false;
}
$mediaIds = $this->uploadMedia($form, $configuration);
$this->mapMediaIds($form->getData(), $mediaIds);
$this->save($form, $configuration);
$this->sendMails($form, $configuration);
return true;
} | php | {
"resource": ""
} |
q259210 | Handler.save | test | private function save(FormInterface $form, FormConfigurationInterface $configuration)
{
$this->eventDispatcher->dispatch(
self::EVENT_FORM_SAVE,
new FormEvent(
$form,
$configuration
)
);
if (!$configuration->getSave()) {
return;
}
$this->entityManager->persist($form->getData());
$this->entityManager->flush();
$this->eventDispatcher->dispatch(
self::EVENT_FORM_SAVED,
new FormEvent(
$form,
$configuration
)
);
} | php | {
"resource": ""
} |
q259211 | Handler.uploadMedia | test | private function uploadMedia(FormInterface $form, FormConfigurationInterface $configuration)
{
$this->attachments = [];
$mediaIds = [];
foreach ($configuration->getFileFields() as $field => $collectionId) {
if (!$form->has($field) || !count($form[$field]->getData())) {
continue;
}
$files = $form[$field]->getData();
$ids = [];
if (!is_array($files)) {
$files = [$files];
}
/** @var UploadedFile $file */
foreach ($files as $file) {
if (!$file instanceof UploadedFile) {
continue;
}
$media = $this->mediaManager->save(
$file,
$this->getMediaData($file, $form, $configuration, $collectionId),
null
);
// save attachments data for swift message
$this->attachments[] = $file;
$ids[] = $media->getId();
}
$mediaIds[$field] = $ids;
}
return $mediaIds;
} | php | {
"resource": ""
} |
q259212 | Handler.mapMediaIds | test | private function mapMediaIds($entity, $mediaIds)
{
$accessor = new PropertyAccessor();
foreach ($mediaIds as $key => $value) {
$accessor->setValue($entity, $key, $value);
}
return $entity;
} | php | {
"resource": ""
} |
q259213 | Handler.getMediaData | test | protected function getMediaData(
UploadedFile $file,
FormInterface $form,
FormConfigurationInterface $configuration,
$collectionId
) {
return [
'collection' => $collectionId,
'locale' => $configuration->getLocale(),
'title' => $file->getClientOriginalName(),
];
} | php | {
"resource": ""
} |
q259214 | MailchimpType.getMailChimpLists | test | private function getMailChimpLists()
{
$lists = [];
// If Milchimp class doesn't exist or no key is set return empty list.
if (!class_exists(\DrewM\MailChimp\MailChimp::class) || !$this->apiKey) {
return $lists;
}
$mailChimp = new \DrewM\MailChimp\MailChimp($this->apiKey);
$response = $mailChimp->get('lists', ['count' => 100]);
if (!isset($response['lists'])) {
return $lists;
}
foreach ($response['lists'] as $list) {
$lists[] = [
'id' => $list['id'],
'name' => $list['name'],
];
}
return $lists;
} | php | {
"resource": ""
} |
q259215 | DynamicListFactory.getBuilder | test | protected function getBuilder($alias = null)
{
if (!$alias || 'default' === $alias) {
$alias = $this->defaultBuilder;
}
if (!$this->builders[$alias]) {
throw new \Exception(sprintf('Bilder with the name "%s" not found.', $alias));
}
return $this->builders[$alias];
} | php | {
"resource": ""
} |
q259216 | AbstractType.getBlockPrefix | test | public function getBlockPrefix()
{
$fqcn = get_class($this);
$name = $this->getName();
// For BC: Use the name as block prefix if one is set
return $name !== $fqcn ? $name : StringUtil::fqcnToBlockPrefix($fqcn);
} | php | {
"resource": ""
} |
q259217 | CollectionStrategyTree.createCollection | test | private function createCollection($title, $parentId, $collectionKey, $locale)
{
$parentCollection = $this->collectionManager->save([
'title' => $title,
'type' => ['id' => 2],
'parent' => $parentId,
'key' => $collectionKey,
'locale' => $locale,
], null);
return $parentCollection->getId();
} | php | {
"resource": ""
} |
q259218 | CollectionStrategyTree.loadCollectionId | test | private function loadCollectionId(
$collectionKey,
$locale
) {
try {
$collection = $this->collectionManager->getByKey($collectionKey, $locale);
if (!$collection) {
return;
}
return $collection->getId();
} catch (\Exception $e) {
// Catch all exception
}
} | php | {
"resource": ""
} |
q259219 | DynamicFormType.getItemWidthNumber | test | private function getItemWidthNumber($width)
{
switch ($width) {
case 'one-sixth':
$itemWidth = 2;
break;
case 'five-sixths':
$itemWidth = 10;
break;
case 'one-quarter':
$itemWidth = 3;
break;
case 'three-quarters':
$itemWidth = 9;
break;
case 'one-third':
$itemWidth = 4;
break;
case 'two-thirds':
$itemWidth = 8;
break;
case 'half':
$itemWidth = 6;
break;
case 'full':
$itemWidth = 12;
break;
default:
$itemWidth = 12;
}
return $itemWidth;
} | php | {
"resource": ""
} |
q259220 | DynamicFormType.getLastWidth | test | private function getLastWidth(&$currentWidthValue, $width, $nextWidth)
{
$widthNumber = $this->getItemWidthNumber($width);
$nextWidthNumber = $this->getItemWidthNumber($nextWidth);
$currentWidthValue += $widthNumber;
if (0 == $currentWidthValue % 12) {
return true;
}
// if next item has no space in current row the current item is last
if (($currentWidthValue % 12) + $nextWidthNumber > 12) {
$currentWidthValue += 12 - $currentWidthValue % 12;
return true;
}
return false;
} | php | {
"resource": ""
} |
q259221 | ErrorHandler.rethrow | test | public static function rethrow(PDOException $e) {
// the 2-character class of the error (if any) has the highest priority
$errorClass = null;
// the 3-character subclass of the error (if any) has a medium priority
$errorSubClass = null;
// the full error code itself has the lowest priority
$error = null;
// if an error code is available
if (!empty($e->getCode())) {
// remember the error code
$error = $e->getCode();
// if the error code is an "SQLSTATE" error
if (strlen($e->getCode()) === 5) {
// remember the class as well
$errorClass = substr($e->getCode(), 0, 2);
// and remember the subclass
$errorSubClass = substr($e->getCode(), 2);
}
}
if ($errorClass === '3D') {
throw new NoDatabaseSelectedError($e->getMessage());
}
elseif ($errorClass === '23') {
throw new IntegrityConstraintViolationException($e->getMessage());
}
elseif ($errorClass === '42') {
if ($errorSubClass === 'S02') {
throw new TableNotFoundError($e->getMessage());
}
elseif ($errorSubClass === 'S22') {
throw new UnknownColumnError($e->getMessage());
}
else {
throw new SyntaxError($e->getMessage());
}
}
else {
if ($error === 1044) {
throw new WrongCredentialsError($e->getMessage());
}
elseif ($error === 1049) {
throw new DatabaseNotFoundError($e->getMessage());
}
else {
throw new Error($e->getMessage());
}
}
} | php | {
"resource": ""
} |
q259222 | PdoDataSource.setHostname | test | public function setHostname($hostname = null) {
$this->hostname = $hostname !== null ? (string) $hostname : null;
return $this;
} | php | {
"resource": ""
} |
q259223 | PdoDataSource.setUnixSocket | test | public function setUnixSocket($unixSocket = null) {
$this->unixSocket = $unixSocket !== null ? (string) $unixSocket : null;
return $this;
} | php | {
"resource": ""
} |
q259224 | PdoDataSource.setMemory | test | public function setMemory($memory = null) {
$this->memory = $memory !== null ? (bool) $memory : null;
return $this;
} | php | {
"resource": ""
} |
q259225 | PdoDataSource.setFilePath | test | public function setFilePath($filePath = null) {
$this->filePath = $filePath !== null ? (string) $filePath : null;
return $this;
} | php | {
"resource": ""
} |
q259226 | PdoDataSource.setDatabaseName | test | public function setDatabaseName($databaseName = null) {
$this->databaseName = $databaseName !== null ? (string) $databaseName : null;
return $this;
} | php | {
"resource": ""
} |
q259227 | PdoDataSource.setCharset | test | public function setCharset($charset = null) {
$this->charset = $charset !== null ? (string) $charset : null;
return $this;
} | php | {
"resource": ""
} |
q259228 | PdoDatabase.ensureConnected | test | private function ensureConnected() {
if ($this->pdo === null) {
try {
$this->pdo = new PDO($this->dsn->getDsn(), $this->dsn->getUsername(), $this->dsn->getPassword());
}
catch (PDOException $e) {
ErrorHandler::rethrow($e);
}
// iterate over all listeners waiting for the connection to be established
foreach ($this->onConnectListeners as $onConnectListener) {
// execute the callback
$onConnectListener($this);
}
// discard the listeners now that they have all been executed
$this->onConnectListeners = [];
$this->dsn = null;
}
if ($this->driverName === null) {
$this->driverName = $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
}
} | php | {
"resource": ""
} |
q259229 | PdoDatabase.configureConnection | test | private function configureConnection(array &$newAttributes = null, array &$oldAttributes = null) {
// if a connection is available
if (isset($this->pdo)) {
// if there are attributes that need to be applied
if (isset($newAttributes)) {
// get the keys and values of the attributes to apply
foreach ($newAttributes as $key => $newValue) {
// if the old state of the connection must be preserved
if (isset($oldAttributes)) {
// retrieve the old value for this attribute
try {
$oldValue = @$this->pdo->getAttribute($key);
}
catch (PDOException $e) {
// the specified attribute is not supported by the driver
$oldValue = null;
}
// if an old value has been found
if (isset($oldValue)) {
// if the old value differs from the new value that we're going to set
if ($oldValue !== $newValue) {
// save the old value so that we're able to restore it later
$oldAttributes[$key] = $oldValue;
}
}
}
// and then set the desired new value
$this->pdo->setAttribute($key, $newValue);
}
// if the old state of the connection doesn't need to be preserved
if (!isset($oldAttributes)) {
// we're done updating attributes for this connection once and for all
$newAttributes = null;
}
}
}
} | php | {
"resource": ""
} |
q259230 | PdoDatabase.selectInternal | test | private function selectInternal(callable $callback, $query, array $bindValues = null) {
$this->normalizeConnection();
try {
// create a prepared statement from the supplied SQL string
$stmt = $this->pdo->prepare($query);
}
catch (PDOException $e) {
ErrorHandler::rethrow($e);
}
// if a performance profiler has been defined
if (isset($this->profiler)) {
$this->profiler->beginMeasurement();
}
/** @var PDOStatement $stmt */
// bind the supplied values to the query and execute it
try {
$stmt->execute($bindValues);
}
catch (PDOException $e) {
ErrorHandler::rethrow($e);
}
// if a performance profiler has been defined
if (isset($this->profiler)) {
$this->profiler->endMeasurement($query, $bindValues, 1);
}
// fetch the desired results from the result set via the supplied callback
$results = $callback($stmt);
$this->denormalizeConnection();
// if the result is empty
if (empty($results) && $stmt->rowCount() === 0) {
// consistently return `null`
return null;
}
// if some results have been found
else {
// return these as extracted by the callback
return $results;
}
} | php | {
"resource": ""
} |
q259231 | IronMQ.getQueues | test | public function getQueues($previous = null, $per_page = self::LIST_QUEUES_PER_PAGE)
{
$url = "projects/{$this->project_id}/queues";
$params = array();
if (!is_null($previous)) {
$params['previous'] = $previous;
}
if ($per_page !== self::LIST_QUEUES_PER_PAGE) {
$params['per_page'] = (int) $per_page;
}
$this->setJsonHeaders();
return self::json_decode($this->apiCall(self::GET, $url, $params))->queues;
} | php | {
"resource": ""
} |
q259232 | IronMQ.getQueue | test | public function getQueue($queue_name)
{
$queue = rawurlencode($queue_name);
$url = "projects/{$this->project_id}/queues/$queue";
$this->setJsonHeaders();
return self::json_decode($this->apiCall(self::GET, $url))->queue;
} | php | {
"resource": ""
} |
q259233 | IronMQ.postMessage | test | public function postMessage($queue_name, $message, $properties = array())
{
$msg = new IronMQMessage($message, $properties);
$req = array(
"messages" => array($msg->asArray()),
);
$this->setJsonHeaders();
$queue = rawurlencode($queue_name);
$url = "projects/{$this->project_id}/queues/$queue/messages";
$res = $this->apiCall(self::POST, $url, $req);
$decoded = self::json_decode($res);
$decoded->id = $decoded->ids[0];
return $decoded;
} | php | {
"resource": ""
} |
q259234 | IronMQ.postMessages | test | public function postMessages($queue_name, $messages, $properties = array())
{
$req = array(
"messages" => array(),
);
foreach ($messages as $message) {
$msg = new IronMQMessage($message, $properties);
array_push($req['messages'], $msg->asArray());
}
$this->setJsonHeaders();
$queue = rawurlencode($queue_name);
$url = "projects/{$this->project_id}/queues/$queue/messages";
$res = $this->apiCall(self::POST, $url, $req);
return self::json_decode($res);
} | php | {
"resource": ""
} |
q259235 | IronMQ.getMessageById | test | public function getMessageById($queue_name, $message_id)
{
$this->setJsonHeaders();
$queue = rawurlencode($queue_name);
$url = "projects/{$this->project_id}/queues/$queue/messages/{$message_id}";
return self::json_decode($this->apiCall(self::GET, $url))->message;
} | php | {
"resource": ""
} |
q259236 | IronMQ.touchMessage | test | public function touchMessage($queue_name, $message_id, $reservation_id, $timeout)
{
$req = array(
"reservation_id" => $reservation_id,
);
if ($timeout !== 0) {
$req['timeout'] = (int) $timeout;
}
$this->setJsonHeaders();
$queue = rawurlencode($queue_name);
$url = "projects/{$this->project_id}/queues/$queue/messages/{$message_id}/touch";
return self::json_decode($this->apiCall(self::POST, $url, $req));
} | php | {
"resource": ""
} |
q259237 | IronMQ.releaseMessage | test | public function releaseMessage($queue_name, $message_id, $reservation_id, $delay)
{
$this->setJsonHeaders();
$queue = rawurlencode($queue_name);
$params = array('reservation_id' => $reservation_id);
if ($delay !== 0) {
$params['delay'] = (int) $delay;
}
$url = "projects/{$this->project_id}/queues/$queue/messages/{$message_id}/release";
return self::json_decode($this->apiCall(self::POST, $url, $params));
} | php | {
"resource": ""
} |
q259238 | IronMQ.addAlerts | test | public function addAlerts($queue_name, $alerts_hash)
{
$this->setJsonHeaders();
$queue = rawurlencode($queue_name);
$url = "projects/{$this->project_id}/queues/$queue";
$options = array(
'queue' => array(
'alerts' => $alerts_hash,
),
);
return self::json_decode($this->apiCall(self::PUT, $url, $options));
} | php | {
"resource": ""
} |
q259239 | IronMQ.deleteAlertById | test | public function deleteAlertById($queue_name, $alert_id)
{
$this->setJsonHeaders();
$queue = rawurlencode($queue_name);
$url = "projects/{$this->project_id}/queues/$queue/alerts/$alert_id";
return self::json_decode($this->apiCall(self::DELETE, $url));
} | php | {
"resource": ""
} |
q259240 | IronMQ.deleteQueue | test | public function deleteQueue($queue_name)
{
$this->setJsonHeaders();
$queue = rawurlencode($queue_name);
$url = "projects/{$this->project_id}/queues/$queue";
return self::json_decode($this->apiCall(self::DELETE, $url));
} | php | {
"resource": ""
} |
q259241 | IronMQ.updateQueue | test | public function updateQueue($queue_name, $options)
{
$this->setJsonHeaders();
$queue = rawurlencode($queue_name);
$url = "projects/{$this->project_id}/queues/$queue";
return self::json_decode($this->apiCall(self::PATCH, $url, array('queue' => $options)));
} | php | {
"resource": ""
} |
q259242 | IronMQ.createQueue | test | public function createQueue($queue_name, $options)
{
$this->setJsonHeaders();
$queue = rawurlencode($queue_name);
$url = "projects/{$this->project_id}/queues/$queue";
return self::json_decode($this->apiCall(self::PUT, $url, array('queue' => $options)));
} | php | {
"resource": ""
} |
q259243 | IronMQ.replaceSubscribers | test | public function replaceSubscribers($queue_name, $subscribers_hash)
{
$this->setJsonHeaders();
$queue = rawurlencode($queue_name);
$url = "projects/{$this->project_id}/queues/$queue/subscribers";
$options = array(
'subscribers' => $subscribers_hash,
);
return self::json_decode($this->apiCall(self::PUT, $url, $options));
} | php | {
"resource": ""
} |
q259244 | IronMQ.removeSubscribers | test | public function removeSubscribers($queue_name, $subscriber_hash)
{
$this->setJsonHeaders();
$queue = rawurlencode($queue_name);
$url = "projects/{$this->project_id}/queues/$queue/subscribers";
$options = array(
'subscribers' => $subscriber_hash,
);
return self::json_decode($this->apiCall(self::DELETE, $url, $options));
} | php | {
"resource": ""
} |
q259245 | GenerateCommand.outputJson | test | protected function outputJson(OutputInterface $output, $data)
{
$json = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
$output->write($json);
} | php | {
"resource": ""
} |
q259246 | GenerateCommand.outputXml | test | protected function outputXml(OutputInterface $output, $data)
{
$doc = new \DOMDocument();
$doc->formatOutput = true;
$doc->appendChild($this->generateXml($doc, $data));
$xml = $doc->saveXML();
$output->write($xml);
} | php | {
"resource": ""
} |
q259247 | GenerateCommand.generateXml | test | protected function generateXml(\DOMDocument $doc, $data)
{
if (is_array($data) && range(0, count($data) - 1) == array_keys($data)) {
// $data is a regular indexed array
$array = $doc->createElement('array');
foreach ($data as $value) {
$entry = $doc->createElement('item');
$entry->appendChild($this->generateXml($doc, $value));
$array->appendChild($entry);
}
return $array;
}
else if (is_array($data) || is_object($data)) {
// $data is an associative array or object
$map = $doc->createElement('map');
foreach ($data as $key => $value) {
$entry = $doc->createElement('item');
$entry->setAttribute('key', $key);
$entry->appendChild($this->generateXml($doc, $value));
$map->appendChild($entry);
}
return $map;
}
else {
// $data is a primitive type
return $doc->createTextNode($data);
}
} | php | {
"resource": ""
} |
q259248 | GenerateCommand.outputCsv | test | protected function outputCsv(InputInterface $input, OutputInterface $output, $data)
{
$delimiter = $input->getOption('delimiter');
$enclosure = $input->getOption('enclosure');
$stream = fopen('php://temp', 'w+');
foreach ($data as $row) {
if ($enclosure === null) {
fputcsv($stream, $this->flattenArray($row), $delimiter);
}
else {
fputcsv($stream, $this->flattenArray($row), $delimiter, $enclosure);
}
}
fseek($stream, 0);
$csv = stream_get_contents($stream);
$output->write($csv);
} | php | {
"resource": ""
} |
q259249 | GenerateCommand.flattenArray | test | protected function flattenArray($data)
{
if (is_array($data) || is_object($data)) {
$buffer = array();
foreach ($data as $item) {
$buffer = array_merge($buffer, $this->flattenArray($item));
}
return $buffer;
}
else {
return (array) $data;
}
} | php | {
"resource": ""
} |
q259250 | CacheClientStatsCommand.execute | test | protected function execute(InputInterface $input, OutputInterface $output)
{
$debug = $input->getOption('debug');
$client = $this->getContainer()->get('beryllium_cache.client');
if (is_object($client) && method_exists($client, 'getStats')) {
$text = $this->formatStats($client->getStats(), $debug);
} else {
$text = 'Active cache client does not have a stats function.';
}
$output->writeln($text);
} | php | {
"resource": ""
} |
q259251 | CacheClientStatsCommand.formatStats | test | public function formatStats($stats, $debug = false)
{
if (!is_array($stats)) {
return "No statistics returned.\n";
}
if (count($stats) == 0) {
return "No statistics returned.\n";
}
$out = "Servers found: " . count($stats) . "\n\n";
foreach ($stats as $host => $item) {
if (!is_array($item) || count($item) == 0) {
$out .= " <error>" . $host . "</error>\n";
continue;
}
$out .= "<info>Host:\t" . $host . "</info>\n";
$out .= "\tUsage: " . $this->formatUsage($item['bytes'], $item['limit_maxbytes']) . "\n";
$out .= "\tUptime: " . $this->formatUptime($item['uptime']) . "\n";
$out .= "\tOpen Connections: " . $item['curr_connections'] . "\n";
$out .= "\tHits: " . $item['get_hits'] . "\n";
$out .= "\tMisses: " . $item['get_misses'] . "\n";
if ($item['get_hits'] + $item['get_misses'] > 0) {
$out .= "\tHelpfulness: " . round(
$item['get_hits'] / ($item['get_hits'] + $item['get_misses']) * 100,
2
) . "%\n";
}
if ($debug) {
$out .= "\n";
foreach ($item as $key => $value) {
$out .= "\t" . $key . ': ' . $value . "\n";
}
}
}
return $out;
} | php | {
"resource": ""
} |
q259252 | CacheClientStatsCommand.formatUsage | test | public function formatUsage($bytes, $maxbytes)
{
if (!is_numeric($maxbytes) || $maxbytes < 1) {
return '(undefined)';
}
$out = round($bytes / $maxbytes, 3) . "% (";
$out .= round($bytes / 1024 / 1024, 2) . 'MB of ';
$out .= round($maxbytes / 1024 / 1024, 2) . 'MB)';
return $out;
} | php | {
"resource": ""
} |
q259253 | CacheClientStatsCommand.formatUptime | test | public function formatUptime($uptime)
{
$days = floor($uptime / 24 / 60 / 60);
$days_remainder = $uptime - ($days * 24 * 60 * 60);
$hours = floor($days_remainder / 60 / 60);
$hours_remainder = $days_remainder - ($hours * 60 * 60);
$minutes = floor($hours_remainder / 60);
$minutes_remainder = $hours_remainder - ($minutes * 60);
$seconds = $minutes_remainder;
$out = $uptime . ' seconds (';
if ($days > 0) {
$out .= $days . ' days, ';
}
if ($hours > 0) {
$out .= $hours . ' hours, ';
}
if ($minutes > 0) {
$out .= $minutes . ' minutes, ';
}
if ($seconds > 0) {
$out .= $seconds . ' seconds';
}
return $out . ')';
} | php | {
"resource": ""
} |
q259254 | MemcacheClient.addServer | test | public function addServer($ip, $port = 11211)
{
if (is_object($this->mem)) {
return $this->mem->addServer($ip, $port);
}
} | php | {
"resource": ""
} |
q259255 | MemcacheClient.addServers | test | public function addServers(array $servers)
{
if (count($servers) == 0) {
return false;
}
foreach ($servers as $ip => $port) {
if (intval($port) == 0) {
$port = null;
}
if ($this->probeServer($ip, $port)) {
$status = $this->addServer($ip, $port);
$this->safe = true;
}
}
} | php | {
"resource": ""
} |
q259256 | MemcacheClient.probeServer | test | public function probeServer($ip, $port)
{
$errno = null;
$errstr = null;
$fp = @fsockopen($ip, $port, $errno, $errstr, $this->sockttl);
if ($fp) {
fclose($fp);
return true;
} else {
return false;
}
} | php | {
"resource": ""
} |
q259257 | MemcacheClient.get | test | public function get($key)
{
if ($this->isSafe()) {
$key = $this->prefix . $key;
return $this->mem->get($key);
}
return false;
} | php | {
"resource": ""
} |
q259258 | MemcacheClient.set | test | public function set($key, $value, $ttl)
{
if ($this->isSafe()) {
$key = $this->prefix . $key;
return $this->mem->set($key, $value, $this->compression, $ttl);
}
return false;
} | php | {
"resource": ""
} |
q259259 | MemcacheClient.delete | test | public function delete($key)
{
if ($this->isSafe()) {
$key = $this->prefix . $key;
return $this->mem->delete($key, 0);
}
return false;
} | php | {
"resource": ""
} |
q259260 | Cache.setClient | test | public function setClient(CacheClientInterface $client)
{
if (is_object($client) && ($client instanceof CacheClientInterface))
$this->client = $client;
else {
throw new \Exception('Invalid Cache Client Interface');
}
} | php | {
"resource": ""
} |
q259261 | Cache.get | test | public function get($key)
{
if ($this->isSafe() && !empty($key)) {
return $this->client->get($key);
}
return false;
} | php | {
"resource": ""
} |
q259262 | Cache.delete | test | public function delete($key)
{
if ($this->isSafe() && !empty($key)) {
return $this->client->delete($key);
}
return false;
} | php | {
"resource": ""
} |
q259263 | FCMMessage.makeInvalidArgumentException | test | protected static function makeInvalidArgumentException($data, $method, $container, $builder)
{
$type = gettype($data);
if (is_object($data)) {
$type = get_class($data);
}
return new InvalidArgumentException(
'The argument for %s::%s must be instanceof %s, %s, null or array. %s given.',
[
self::class, $method, $container, $builder, $type,
]
);
} | php | {
"resource": ""
} |
q259264 | FCMMessage.populateBuilder | test | protected static function populateBuilder($builder, array $map, array $data)
{
foreach ($map as $key => $method) {
$value = Arr::get($data, $key);
$builder->{$method}($value);
}
return $builder;
} | php | {
"resource": ""
} |
q259265 | FCMMessage.options | test | public function options($options = null)
{
if (is_array($options)) {
if ($this->options && $this->options instanceof Options) {
$options = array_merge($this->options->toArray(), $options);
}
if (! Arr::has($options, 'priority')) {
$options['priority'] = OptionsPriorities::normal;
}
$builder = new OptionsBuilder();
$options = static::populateBuilder($builder, static::OPTIONS_MAP, $options);
}
if ($options instanceof Options) {
$this->options = $options;
} elseif ($options instanceof OptionsBuilder) {
$this->options = $options->build();
} elseif (! is_null($options)) {
throw static::makeInvalidArgumentException(
$options,
'options',
Options::class,
OptionsBuilder::class
);
}
return $this;
} | php | {
"resource": ""
} |
q259266 | FCMMessage.notification | test | public function notification($notification = null)
{
if (is_array($notification)) {
if ($this->notification && $this->notification instanceof PayloadNotification) {
$notification = array_merge($this->notification->toArray(), $notification);
}
$builder = new PayloadNotificationBuilder();
$notification = static::populateBuilder($builder, static::NOTIFICATION_MAP, $notification);
}
if ($notification instanceof PayloadNotification) {
$this->notification = $notification;
} elseif ($notification instanceof PayloadNotificationBuilder) {
$this->notification = $notification->build();
} elseif (! is_null($notification)) {
throw static::makeInvalidArgumentException(
$notification,
'notification',
PayloadNotification::class,
PayloadNotificationBuilder::class
);
}
return $this;
} | php | {
"resource": ""
} |
q259267 | FCMMessage.data | test | public function data($data = null)
{
if (is_array($data)) {
if ($this->data && $this->data instanceof PayloadData) {
$data = array_merge($this->data->toArray(), $data);
}
$data = (new PayloadDataBuilder())->setData($data);
}
if ($data instanceof PayloadData) {
$this->data = $data;
} elseif ($data instanceof PayloadDataBuilder) {
$this->data = $data->build();
} elseif (! is_null($data)) {
throw static::makeInvalidArgumentException(
$data,
'data',
PayloadData::class,
PayloadDataBuilder::class
);
}
return $this;
} | php | {
"resource": ""
} |
q259268 | LoggerLayoutXml.encodeCDATA | test | private function encodeCDATA($string) {
$string = str_replace(self::CDATA_END, self::CDATA_EMBEDDED_END, $string);
return self::CDATA_START . $string . self::CDATA_END;
} | php | {
"resource": ""
} |
q259269 | UrlBuilder.getNonAuthenticationUrl | test | public function getNonAuthenticationUrl(
$action,
\FACTFinder\Util\Parameters $parameters
) {
$configuration = $this->configuration;
$this->ensureChannelParameter($parameters);
$url = $this->buildAddress($action)
. (count($parameters) ? '?' : '') . $parameters->toJavaQueryString();
return $url;
} | php | {
"resource": ""
} |
q259270 | UrlBuilder.getAuthenticationUrl | test | public function getAuthenticationUrl(
$action,
\FACTFinder\Util\Parameters $parameters
) {
$this->ensureChannelParameter($parameters);
$c = $this->configuration;
if ($c->isAdvancedAuthenticationType())
return $this->getAdvancedAuthenticationUrl($action, $parameters);
else if ($c->isSimpleAuthenticationType())
return $this->getSimpleAuthenticationUrl($action, $parameters);
else if ($c->isHttpAuthenticationType())
return $this->getHttpAuthenticationUrl($action, $parameters);
else
throw new \Exception('Invalid authentication type configured.');
} | php | {
"resource": ""
} |
q259271 | UrlBuilder.getAdvancedAuthenticationUrl | test | protected function getAdvancedAuthenticationUrl(
$action,
\FACTFinder\Util\Parameters $parameters
) {
$configuration = $this->configuration;
$ts = time() . '000'; //milliseconds needed
$prefix = $configuration->getAuthenticationPrefix();
$postfix = $configuration->getAuthenticationPostfix();
$hashedPW = md5($prefix
. $ts
. md5($configuration->getPassword())
. $postfix);
$authenticationParameters = 'timestamp=' . $ts
. '&username=' . $configuration->getUserName()
. '&password=' . $hashedPW;
$url = $this->buildAddress($action)
. '?' . $parameters->toJavaQueryString()
. (count($parameters) ? '&' : '') . $authenticationParameters;
$this->log->info("Request Url: " . $url);
return $url;
} | php | {
"resource": ""
} |
q259272 | UrlBuilder.getSimpleAuthenticationUrl | test | protected function getSimpleAuthenticationUrl(
$action,
\FACTFinder\Util\Parameters $parameters
) {
$configuration = $this->configuration;
$ts = time() . '000'; //milliseconds needed but won't be considered
$authenticationParameters = "timestamp=" . $ts
. '&username=' . $configuration->getUserName()
. '&password=' . md5($configuration->getPassword());
$url = $this->buildAddress($action)
. '?' . $parameters->toJavaQueryString()
. (count($parameters) ? '&' : '') . $authenticationParameters;
$this->log->info("Request Url: " . $url);
return $url;
} | php | {
"resource": ""
} |
q259273 | UrlBuilder.getHttpAuthenticationUrl | test | protected function getHttpAuthenticationUrl(
$action,
\FACTFinder\Util\Parameters $parameters
) {
$configuration = $this->configuration;
$authentication = sprintf(
'%s:%s@',
$configuration->getUserName(),
$configuration->getPassword()
);
if ($authentication == ':@') $authentication = '';
$url = $this->buildAddress($action, true)
. (count($parameters) ? '?' : '') . $parameters->toJavaQueryString();
$this->log->info("Request Url: " . $url);
return $url;
} | php | {
"resource": ""
} |
q259274 | UrlBuilder.ensureChannelParameter | test | protected function ensureChannelParameter($parameters) {
if ((!isset($parameters['channel'])
|| $parameters['channel'] == '')
&& $this->configuration->getChannel() != ''
) {
$parameters['channel'] = $this->configuration->getChannel();
}
} | php | {
"resource": ""
} |
q259275 | SimilarRecords.setProductID | test | public function setProductID($productID)
{
$parameters = $this->request->getParameters();
$parameters['id'] = $productID;
$this->upToDate = false;
} | php | {
"resource": ""
} |
q259276 | SimilarRecords.getSimilarAttributes | test | public function getSimilarAttributes()
{
if (is_null($this->similarAttributes)
|| !$this->upToDate
) {
$this->similarAttributes = $this->createSimilarAttributes();
$this->upToDate = true;
}
return $this->similarAttributes;
} | php | {
"resource": ""
} |
q259277 | SimilarRecords.getSimilarRecords | test | public function getSimilarRecords()
{
if (is_null($this->similarRecords)
|| !$this->upToDate
) {
$this->request->resetLoaded();
$this->similarRecords = $this->createSimilarRecords();
$this->upToDate = true;
}
return $this->similarRecords;
} | php | {
"resource": ""
} |
q259278 | LoggerAppenderFile.write | test | protected function write($string) {
// Lazy file open
if(!isset($this->fp)) {
if ($this->openFile() === false) {
return; // Do not write if file open failed.
}
}
if ($this->locking) {
$this->writeWithLocking($string);
} else {
$this->writeWithoutLocking($string);
}
} | php | {
"resource": ""
} |
q259279 | LoggerAutoloader.autoload | test | public static function autoload($className) {
if(isset(self::$classes[$className])) {
include dirname(__FILE__) . self::$classes[$className];
}
} | php | {
"resource": ""
} |
q259280 | LoggerAppenderConsole.setTarget | test | public function setTarget($target) {
$value = trim($target);
if ($value == self::STDOUT || strtoupper($value) == 'STDOUT') {
$this->target = self::STDOUT;
} elseif ($value == self::STDERR || strtoupper($value) == 'STDERR') {
$this->target = self::STDERR;
} else {
$target = var_export($target);
$this->warn("Invalid value given for 'target' property: [$target]. Property not set.");
}
} | php | {
"resource": ""
} |
q259281 | Import.triggerDataImport | test | public function triggerDataImport($download = false)
{
//this function changes parameters, action, ... so reload of response is neccessary
$this->request->resetLoaded();
$this->request->setAction('Import.ff');
$this->parameters['download'] = $download ? 'true' : 'false';
// TODO: Parse the response XML into some nice domain object.
return $this->getResponseContent();
} | php | {
"resource": ""
} |
q259282 | Import.triggerSuggestImport | test | public function triggerSuggestImport($download = false)
{
//this function changes parameters, action, ... so reload of response is neccessary
$this->request->resetLoaded();
$this->request->setAction('Import.ff');
$this->parameters['download'] = $download ? 'true' : 'false';
$this->parameters['type'] = 'suggest';
$report = $this->getResponseContent();
// Clean up for next import
unset($this->parameters['type']);
// TODO: Parse the response XML into some nice domain object.
return $report;
} | php | {
"resource": ""
} |
q259283 | ParametersConverter.applyParameterMappings | test | protected function applyParameterMappings($parameters, $mappingRules)
{
foreach ($mappingRules as $k => $v)
{
if ($k != $v && isset($parameters[$k]))
{
$parameters[$v] = $parameters[$k];
unset($parameters[$k]);
}
}
} | php | {
"resource": ""
} |
q259284 | ParametersConverter.ensureChannelParameter | test | protected function ensureChannelParameter($parameters)
{
if (!isset($parameters['channel']) || strlen($parameters['channel']) == 0)
$parameters['channel'] = $this->configuration->getChannel();
} | php | {
"resource": ""
} |
q259285 | ParametersConverter.addRequiredParameters | test | protected function addRequiredParameters($parameters, $requireRules)
{
foreach ($requireRules as $k => $v)
if (!isset($parameters[$k]))
$parameters[$k] = $v;
} | php | {
"resource": ""
} |
q259286 | LoggerAppenderPool.add | test | public static function add(LoggerAppender $appender) {
$name = $appender->getName();
if(empty($name)) {
trigger_error('log4php: Cannot add unnamed appender to pool.', E_USER_WARNING);
return;
}
if (isset(self::$appenders[$name])) {
trigger_error("log4php: Appender [$name] already exists in pool. Overwriting existing appender.", E_USER_WARNING);
}
self::$appenders[$name] = $appender;
} | php | {
"resource": ""
} |
q259287 | LoggerAppenderPool.get | test | public static function get($name) {
return isset(self::$appenders[$name]) ? self::$appenders[$name] : null;
} | php | {
"resource": ""
} |
q259288 | Logger.trace | test | public function trace($message, $throwable = null) {
$this->log(LoggerLevel::getLevelTrace(), $message, $throwable);
} | php | {
"resource": ""
} |
q259289 | Logger.debug | test | public function debug($message, $throwable = null) {
$this->log(LoggerLevel::getLevelDebug(), $message, $throwable);
} | php | {
"resource": ""
} |
q259290 | Logger.warn | test | public function warn($message, $throwable = null) {
$this->log(LoggerLevel::getLevelWarn(), $message, $throwable);
} | php | {
"resource": ""
} |
q259291 | Logger.log | test | public function log(LoggerLevel $level, $message, $throwable = null) {
if($this->isEnabledFor($level)) {
$event = new LoggerLoggingEvent($this->fqcn, $this, $level, $message, null, $throwable);
$this->callAppenders($event);
}
// Forward the event upstream if additivity is turned on
if(isset($this->parent) && $this->getAdditivity()) {
// Use the event if already created
if (isset($event)) {
$this->parent->logEvent($event);
} else {
$this->parent->log($level, $message, $throwable);
}
}
} | php | {
"resource": ""
} |
q259292 | Logger.logEvent | test | public function logEvent(LoggerLoggingEvent $event) {
if($this->isEnabledFor($event->getLevel())) {
$this->callAppenders($event);
}
// Forward the event upstream if additivity is turned on
if(isset($this->parent) && $this->getAdditivity()) {
$this->parent->logEvent($event);
}
} | php | {
"resource": ""
} |
q259293 | Logger.forcedLog | test | public function forcedLog($fqcn, $throwable, LoggerLevel $level, $message) {
$event = new LoggerLoggingEvent($fqcn, $this, $level, $message, null, $throwable);
$this->callAppenders($event);
// Forward the event upstream if additivity is turned on
if(isset($this->parent) && $this->getAdditivity()) {
$this->parent->logEvent($event);
}
} | php | {
"resource": ""
} |
q259294 | Logger.removeAppender | test | public function removeAppender($appender) {
if($appender instanceof LoggerAppender) {
$appender->close();
unset($this->appenders[$appender->getName()]);
} else if (is_string($appender) and isset($this->appenders[$appender])) {
$this->appenders[$appender]->close();
unset($this->appenders[$appender]);
}
} | php | {
"resource": ""
} |
q259295 | Logger.getEffectiveLevel | test | public function getEffectiveLevel() {
for($logger = $this; $logger !== null; $logger = $logger->getParent()) {
if($logger->getLevel() !== null) {
return $logger->getLevel();
}
}
} | php | {
"resource": ""
} |
q259296 | Logger.getHierarchy | test | public static function getHierarchy() {
if(!isset(self::$hierarchy)) {
self::$hierarchy = new LoggerHierarchy(new LoggerRoot());
}
return self::$hierarchy;
} | php | {
"resource": ""
} |
q259297 | Logger.getLogger | test | public static function getLogger($name) {
if(!self::isInitialized()) {
self::configure();
}
return self::getHierarchy()->getLogger($name);
} | php | {
"resource": ""
} |
q259298 | Logger.resetConfiguration | test | public static function resetConfiguration() {
self::getHierarchy()->resetConfiguration();
self::getHierarchy()->clear(); // TODO: clear or not?
self::$initialized = false;
} | php | {
"resource": ""
} |
q259299 | Logger.configure | test | public static function configure($configuration = null, $configurator = null) {
self::resetConfiguration();
$configurator = self::getConfigurator($configurator);
$configurator->configure(self::getHierarchy(), $configuration);
self::$initialized = true;
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.