_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q262300 | RollingCurl.request | test | public function request($url, $method = "GET", $postData = null, $headers = null, $options = null)
{
$newRequest = new Request($url, $method);
if ($postData) {
$newRequest->setPostData($postData);
}
if ($headers) {
$newRequest->setHeaders($headers);
}
if ($options) {
$newRequest->setOptions($options);
}
return $this->add($newRequest);
} | php | {
"resource": ""
} |
q262301 | RollingCurl.post | test | public function post($url, $postData = null, $headers = null, $options = null)
{
return $this->request($url, "POST", $postData, $headers, $options);
} | php | {
"resource": ""
} |
q262302 | RollingCurl.put | test | public function put($url, $putData = null, $headers = null, $options = null)
{
return $this->request($url, "PUT", $putData, $headers, $options);
} | php | {
"resource": ""
} |
q262303 | RollingCurl.delete | test | public function delete($url, $headers = null, $options = null)
{
return $this->request($url, "DELETE", null, $headers, $options);
} | php | {
"resource": ""
} |
q262304 | RollingCurl.execute | test | public function execute()
{
$master = curl_multi_init();
// start the first batch of requests
$firstBatch = $this->getNextPendingRequests($this->getSimultaneousLimit());
// what a silly "error"
if (count($firstBatch) == 0) {
return;
}
foreach ($firstBatch as $request) {
// setup the curl request, queue it up, and put it in the active array
$ch = curl_init();
$options = $this->prepareRequestOptions($request);
curl_setopt_array($ch, $options);
curl_multi_add_handle($master, $ch);
$this->activeRequests[(string)$ch] = $request;
}
do {
while (($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM) {
;
}
if ($execrun != CURLM_OK) {
// todo: throw exception
break;
}
// a request was just completed -- find out which one
while ($transfer = curl_multi_info_read($master)) {
// get the request object back and put the curl response into it
$key = (string)$transfer['handle'];
$request = $this->activeRequests[$key];
$request->setResponseText(curl_multi_getcontent($transfer['handle']));
$request->setResponseErrno(curl_errno($transfer['handle']));
$request->setResponseError(curl_error($transfer['handle']));
$request->setResponseInfo(curl_getinfo($transfer['handle']));
// if there is a callback, run it
if (is_callable($this->callback)) {
$callback = $this->callback;
$callback($request, $this);
}
// remove the request from the list of active requests
unset($this->activeRequests[$key]);
// move the request to the completed set
$this->completedRequests[] = $request;
// start a new request (it's important to do this before removing the old one)
if ($nextRequest = $this->getNextPendingRequest()) {
// setup the curl request, queue it up, and put it in the active array
$ch = curl_init();
$options = $this->prepareRequestOptions($nextRequest);
curl_setopt_array($ch, $options);
curl_multi_add_handle($master, $ch);
$this->activeRequests[(string)$ch] = $nextRequest;
}
// remove the curl handle that just completed
curl_multi_remove_handle($master, $transfer['handle']);
}
if ($running) {
curl_multi_select($master, $this->timeout);
}
// keep the loop going as long as multi_exec says it is running
} while ($running);
curl_multi_close($master);
} | php | {
"resource": ""
} |
q262305 | RollingCurl.addOptions | test | public function addOptions($options)
{
if (!is_array($options)) {
throw new \InvalidArgumentException("options must be an array");
}
$this->options = $options + $this->options;
return $this;
} | php | {
"resource": ""
} |
q262306 | Cluster.onRequestExecute | test | public function onRequestExecute(RequestEvent $event)
{
$request = $event->getRequest();
//Make sure we have some nodes to choose from
if (count($this->nodes) === 0) {
throw new RuntimeException("No nodes in cluster, request failed");
}
//Choose a random node
$request->node = $this->nodes[array_rand($this->nodes)];
} | php | {
"resource": ""
} |
q262307 | Cluster.autodetect_parseNodes | test | private function autodetect_parseNodes()
{
foreach ($this->nodes as $node) {
try {
$client = new Client('http://' . $node['host'] . ':' . $node['port']);
$request = $client->get('/_nodes/http');
$response = $request->send()->json();
foreach ($response['nodes'] as $newNode) {
//we don't want http-inaccessible nodes
if (!isset($newNode['http_address'])) {
continue;
}
preg_match('/inet\[\/([0-9\.]+):([0-9]+)\]/i', $newNode['http_address'], $match);
$tNode = array('host' => $match[1], 'port' => $match[2]);
//use host as key so that we don't add duplicates
$this->nodes[$match[1]] = $tNode;
}
//we have the complete node list, no need to keep checking
break;
} catch (\Guzzle\Http\Exception\BadResponseException $e) {
//error with this node, continue onto the next one
}
}
} | php | {
"resource": ""
} |
q262308 | IndexDocumentRequest.document | test | public function document($value, $id = null, $update = false)
{
if (!$this->batch instanceof BatchCommand) {
throw new exceptions\RuntimeException("Cannot add a new document to an external BatchCommandInterface");
}
$this->finalizeCurrentCommand();
if (is_array($value)) {
$this->params['doc'] = $value;
} elseif (is_string($value)) {
$this->params['doc'] = json_decode($value, true);
}
if ($id !== null) {
$this->currentCommand->id($id)
->action('put');
$this->params['update'] = $update;
} else {
$this->currentCommand->action('post');
$this->params['update'] = false;
}
return $this;
} | php | {
"resource": ""
} |
q262309 | IndexDocumentRequest.execute | test | public function execute()
{
/*
foreach (array('index', 'type') as $key) {
if (!isset($this->params[$key])) {
throw new exceptions\RuntimeException($key." cannot be empty.");
}
}
foreach (array('index', 'type') as $key) {
if (count($this->params[$key]) > 1) {
throw new exceptions\RuntimeException("Only one ".$key." may be inserted into at a time.");
}
}
*/
$this->finalizeCurrentCommand();
//if this is an internal Sherlock BatchCommand, make sure index/types/action are filled
if ($this->batch instanceof BatchCommand) {
if (isset($this->params['index'][0])) {
$this->batch->fillIndex($this->params['index'][0]);
}
if (isset($this->params['type'][0])) {
$this->batch->fillType($this->params['type'][0]);
}
}
return parent::execute();
} | php | {
"resource": ""
} |
q262310 | IndexDocumentRequest.finalizeCurrentCommand | test | private function finalizeCurrentCommand()
{
if ($this->batch instanceof BatchCommand && $this->currentCommand !== null) {
if (isset($this->params['update']) && $this->params['update'] === true) {
$this->currentCommand->action('post')->suffix('_update');
if ($this->params['doc'] !== null) {
$data["doc"] = $this->params['doc'];
}
if ($this->params['updateScript'] !== null) {
$data["script"] = $this->params['updateScript'];
}
if ($this->params['updateParams'] !== null) {
$data["params"] = $this->params['updateParams'];
}
if ($this->params['updateUpsert'] !== null) {
$data["upsert"] = $this->params['updateUpsert'];
}
$this->currentCommand->data($data);
} else {
$this->currentCommand->data($this->params['doc']);
}
$this->batch->addCommand($this->currentCommand);
$this->params['update'] = false;
}
$this->currentCommand = new Command();
} | php | {
"resource": ""
} |
q262311 | IndexDocumentRequest.currentCommandCheck | test | private function currentCommandCheck()
{
$this->params['update'] = true;
if ($this->currentCommand === null) {
$this->currentCommand = new Command();
}
} | php | {
"resource": ""
} |
q262312 | GalleryBehavior.getGallery | test | public function getGallery(Model $Model, $object_id = null)
{
$Album = new Album();
if (!$object_id) {
$object_id = $Model->id;
}
return $Album->getAttachedAlbum($Model->alias, $object_id);
} | php | {
"resource": ""
} |
q262313 | Album.init | test | public function init($model = null, $model_id = null)
{
# If there is a Model and ModelID on parameters, get or create a folder for it
if ($model && $model_id) {
# Searching for folder that belongs to this particular $model and $model_id
if (!$album = $this->getAttachedAlbum($model, $model_id)) {
# If there is no Album , lets create one for it
$album = $this->createInitAlbum($model, $model_id);
}
} else {
# If there is no model on parameters, lets create a generic folder
$album = $this->createInitAlbum(null, null);
}
return $album;
} | php | {
"resource": ""
} |
q262314 | Album.createInitAlbum | test | private function createInitAlbum($model = null, $model_id = null)
{
$this->save(
array(
'Album' => array(
'model' => $model,
'model_id' => $model_id,
'status' => 'draft',
'tags' => '',
'title' => $this->generateAlbumName($model, $model_id)
)
)
);
return $this->read(null);
} | php | {
"resource": ""
} |
q262315 | Album.generateAlbumName | test | private function generateAlbumName($model = null, $model_id = null)
{
$name = 'Album - ' . rand(111, 999);
if ($model && $model_id) {
$name = Inflector::humanize('Album ' . $model . ' - ' . $model_id);
}
return $name;
} | php | {
"resource": ""
} |
q262316 | AlbumsController.upload | test | public function upload($model = null, $model_id = null)
{
ini_set("memory_limit", "10000M");
if (isset($this->params['gallery_id']) && !empty($this->params['gallery_id'])) {
$album = $this->Album->findById($this->params['gallery_id']);
} else {
# If the gallery doesnt exists, create a new one and redirect back to this page with the
# gallery_id
$album = $this->Album->init($model, $model_id);
# Redirect back to this page with an album ID
$this->redirect(
array(
'action' => 'upload',
'gallery_id' => $album['Album']['id']
)
);
}
$files = $album['Picture'];
$this->set(compact('model', 'model_id', 'album', 'files'));
} | php | {
"resource": ""
} |
q262317 | Picture.afterDelete | test | public function afterDelete()
{
if( $this->pictureToDelete ) {
$this->deleteVersions($this->pictureToDelete);
$this->pictureToDelete = null;
}
} | php | {
"resource": ""
} |
q262318 | Picture.getResizeToSize | test | public function getResizeToSize()
{
$width = $height = 0;
if (Configure::check('GalleryOptions.Pictures.resize_to.0')) {
$width = Configure::read('GalleryOptions.Pictures.resize_to.0');
}
if (Configure::check('GalleryOptions.Pictures.resize_to.1')) {
$height = Configure::read('GalleryOptions.Pictures.resize_to.1');
}
$crop = Configure::read('GalleryOptions.Pictures.resize_to.2');
$action = $crop ? "crop" : "";
return array(
'width' => $width,
'height' => $height,
'action' => $action
);
} | php | {
"resource": ""
} |
q262319 | Picture.addImageStyles | test | public function addImageStyles($path)
{
# Styles configured in bootstrap.php
$sizes = Configure::read('GalleryOptions.Pictures.styles');
$links = array();
if (count($sizes)) {
$root_url = WWW_ROOT;
$relative_url = Router::url('/');
# Current filename
$filename = end(explode("/", $path));
foreach ($sizes as $sizename => $size) {
# Filename with size prefix. E.g: small-filename.jpg
$modified = $sizename . "-" . $filename;
# Get final path replacing absolute URl to application relative URL
$final_path = str_replace($root_url, $relative_url, str_replace($filename, $modified, $path));
# Add to array
$links[$sizename] = $final_path;
}
}
return $links;
} | php | {
"resource": ""
} |
q262320 | Picture.deleteVersions | test | public function deleteVersions($id)
{
# Remove all versions of the picture
$pictures = $this->find(
'all',
array(
'conditions' => array(
'Picture.main_id' => $id
)
)
);
if (count($pictures)) {
foreach ($pictures as $pic) {
# Remove file
if (unlink($pic['Picture']['path'])) {
# Remove from database
$this->delete($pic['Picture']['id'], array('callback' => false));
}
}
}
return true;
} | php | {
"resource": ""
} |
q262321 | Picture.savePicture | test | public function savePicture($album_id, $filename, $path, $main_id = null, $style = 'full')
{
$this->create();
# Save the record in database
$picture = array(
'Picture' => array(
'album_id' => $album_id,
'name' => $filename,
'path' => $path,
'main_id' => $main_id,
'style' => $style
)
);
$this->save($picture);
return $this->id;
} | php | {
"resource": ""
} |
q262322 | Picture.createExtraImages | test | public function createExtraImages($styles, $filename, $tmp_name, $album_id, $main_id, $image_name)
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (count($styles)) {
foreach ($styles as $style_name => $style) {
$width = $style[0];
$height = $style[1];
$crop = $style[2] ? "crop" : "";
# eg: medium-1982318927313.jpg
$custom_filename = $style_name . '-' . $image_name . '.' . $ext;
$path = $this->generateFilePath($album_id, $custom_filename);
try {
$this->uploadFile(
$path,
$album_id,
$style_name . '-' . $filename,
$tmp_name,
$width,
$height,
$crop,
true,
$main_id,
$style_name
);
} catch (ForbiddenException $e) {
throw new ForbiddenException($e->getMessage());
}
}
}
} | php | {
"resource": ""
} |
q262323 | Zebra_Image.Zebra_Image | test | function Zebra_Image()
{
// set default values for properties
$this->chmod_value = 0755;
$this->error = 0;
$this->jpeg_quality = 85;
$this->png_compression = 9;
$this->preserve_aspect_ratio = $this->preserve_time = $this->enlarge_smaller_images = true;
$this->sharpen_images = false;
$this->source_path = $this->target_path = '';
} | php | {
"resource": ""
} |
q262324 | Zebra_Image._prepare_image | test | function _prepare_image($width, $height, $background_color = '#FFFFFF')
{
// create a blank image
$identifier = imagecreatetruecolor((int)$width <= 0 ? 1 : (int)$width, (int)$height <= 0 ? 1 : (int)$height);
// if we are creating a PNG image
if ($this->target_type == 'png' && $background_color == -1) {
// disable blending
imagealphablending($identifier, false);
// allocate a transparent color
$transparent_color = imagecolorallocatealpha($identifier, 0, 0, 0, 127);
// fill the image with the transparent color
imagefill($identifier, 0, 0, $transparent_color);
//save full alpha channel information
imagesavealpha($identifier, true);
// if source image is a transparent GIF
} elseif ($this->target_type == 'gif' && $background_color == -1 && $this->source_transparent_color_index >= 0) {
// allocate the source image's transparent color also to the new image resource
$transparent_color = imagecolorallocate(
$identifier,
$this->source_transparent_color['red'],
$this->source_transparent_color['green'],
$this->source_transparent_color['blue']
);
// fill the background of the new image with transparent color
imagefill($identifier, 0, 0, $transparent_color);
// from now on, every pixel having the same RGB as the transparent color will be transparent
imagecolortransparent($identifier, $transparent_color);
// for other image types
} else {
// if transparent background color specified, revert to white
if ($background_color == -1) {
$background_color = '#FFFFFF';
}
// convert hex color to rgb
$background_color = $this->_hex2rgb($background_color);
// prepare the background color
$background_color = imagecolorallocate(
$identifier,
$background_color['r'],
$background_color['g'],
$background_color['b']
);
// fill the image with the background color
imagefill($identifier, 0, 0, $background_color);
}
// return the image's identifier
return $identifier;
} | php | {
"resource": ""
} |
q262325 | InstallController.configure | test | public function configure()
{
$files_path = WWW_ROOT . 'files' . DS;
if (!file_exists($files_path)) {
mkdir($files_path, 0755);
}
$galleries_path = $files_path . 'gallery' . DS;
if (!file_exists($galleries_path)) {
mkdir($galleries_path, 0755);
}
$this->_configureDatabase();
$this->Session->setFlash('Success! Gallery is now installed in your app.');
$this->redirect(
array(
'controller' => 'gallery',
'action' => 'index',
'plugin' => 'gallery'
)
);
$this->render(false, false);
} | php | {
"resource": ""
} |
q262326 | InstallController._configureDatabase | test | private function _configureDatabase()
{
try {
$db = ConnectionManager::getDataSource('default');
if (!$db->isConnected()) {
throw new Exception("You need to connect to a MySQL Database to use this Plugin.");
}
/** Verify if the tables already exists */
if (!$this->_checkTables($db->listSources())) {
$this->_setupDatabase($db);
}
# Create config file
$this->_createConfigFile();
return;
} catch (Exception $e) {
$this->Session->setFlash($e->getMessage());
$this->redirect('/');
}
} | php | {
"resource": ""
} |
q262327 | InstallController._createConfigFile | test | private function _createConfigFile()
{
$destinationPath = App::pluginPath('Gallery') . 'config' . DS . 'config.php';
if (!file_exists($destinationPath)) {
$configFile = new File(App::pluginPath('Gallery') . 'config' . DS . 'config.php.install');
$configFile->copy($destinationPath);
}
} | php | {
"resource": ""
} |
q262328 | Generate_Docs.checkSummaries | test | public function checkSummaries() {
$need_summaries = array();
foreach ( $this->service['operations'] as $method => $info ) {
if ( ! isset( $info['summary'] ) ) {
$need_summaries[] = $method;
}
}
if ( ! empty( $need_summaries ) ) {
echo PHP_EOL;
echo 'Please set summaries for all operations to generate docs.' . PHP_EOL;
echo 'The following operations are missing a \'summary\' value in service.php:' . PHP_EOL;
foreach ( $need_summaries as $method ) {
echo ' ' . $method . PHP_EOL;
}
echo PHP_EOL;
exit;
}
} | php | {
"resource": ""
} |
q262329 | Generate_Docs.generate | test | public function generate() {
ob_start();
foreach ( $this->service['operations'] as $method => $info ) {
// Add method to info array for more convenient templates
$info['method'] = $method;
// Heading
echo $this->template( $this->tmpl_heading, $info );
// Code Block start
echo $this->template( $this->tmpl_code_block_start, $info );
if ( isset( $info['parameters'] ) ) {
// Method call (with parameters) start
echo $this->template( $this->tmpl_method_with_params_start, $info );
// Parameters
foreach ( $info['parameters'] as $param => $param_info ) {
$param_info['param'] = $param;
echo $this->template( $this->tmpl_method_parameter, $param_info );
}
// Method call end
echo $this->template( $this->tmpl_method_with_params_end, $info );
}else {
// Method call (no parameters)
echo $this->template( $this->tmpl_method_without_params, $info );
}
// Code Block end
echo $this->template( $this->tmpl_code_block_end, $info );
}
$this->checkTestCoverage();
$this->docs_markdown = ob_get_clean();
return $this->docs_markdown;
} | php | {
"resource": ""
} |
q262330 | GalleryHelper.link | test | public function link($model = null, $model_id = null, $html_options = array())
{
return $this->_View->Html->link(
__('Upload pictures'),
array(
'controller' => 'albums',
'action' => 'upload',
'plugin' => 'gallery',
$model,
$model_id
),
$html_options
);
} | php | {
"resource": ""
} |
q262331 | GalleryHelper.showroom | test | public function showroom(
$model = null,
$model_id = null,
$album_id = null,
$style = 'medium',
$html_options = array('jquery' => true, 'swipebox' => true))
{
$album = $this->getAlbum($model, $model_id, $album_id);
if (!empty($album)) {
# Load scripts for the showroom (jquery, bootstrap, swipebox)
$this->_loadScripts($html_options);
# Render the showroom
$this->showroomTmpl($album, $style);
} else {
# Album doesn't exists
$this->_noPhotosMessageTmpl();
}
return;
} | php | {
"resource": ""
} |
q262332 | GalleryHelper.showroomTmpl | test | public function showroomTmpl($album, $style = 'medium')
{
if (empty($album['Picture'])) {
$this->_noPhotosMessageTmpl();
} else {
foreach ($album['Picture'] as $picture) {
$this->_thumbnailTmpl($picture, $style);
}
}
} | php | {
"resource": ""
} |
q262333 | GalleryHelper._loadScripts | test | private function _loadScripts($scripts = array('jquery' => true, 'swipebox' => true))
{
if (!isset($scripts['jquery']) || (isset($scripts['jquery']) && $scripts['jquery'] == true)) {
echo $this->_View->Html->script(
'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',
array('block' => 'script'));
}
if (!isset($scripts['swipebox']) || (isset($scripts['swipebox']) && $scripts['swipebox'] == true)) {
echo $this->_View->Html->css(
'https://cdnjs.cloudflare.com/ajax/libs/jquery.swipebox/1.3.0.2/css/swipebox.min.css',
array('block' => 'css'));
echo $this->_View->Html->script(array(
'https://cdnjs.cloudflare.com/ajax/libs/jquery.swipebox/1.3.0.2/js/jquery.swipebox.min.js',
'Gallery.interface'
),
array('block' => 'script'));
}
} | php | {
"resource": ""
} |
q262334 | PicturesController.delete | test | public function delete($id)
{
# Delete the picture and all its versions
$this->Picture->delete($id);
$this->render(false, false);
} | php | {
"resource": ""
} |
q262335 | PicturesController.sort | test | public function sort()
{
if ($this->request->is('post')) {
$order = explode(",", $_POST['order']);
$i = 1;
foreach ($order as $photo) {
$this->Picture->read(null, $photo);
$this->Picture->set('order', $i);
$this->Picture->save();
$i++;
}
}
$this->render(false, false);
} | php | {
"resource": ""
} |
q262336 | YouTube.listChannelSections | test | public function listChannelSections($parameters)
{
$this->apiUri = $this->baseUri . '/channelSections';
$this->filters = [
'channelId',
'id',
];
if (empty($parameters) || !isset($parameters['part'])) {
throw new \InvalidArgumentException(
'Missing the required "part" parameter.'
);
}
$response = $this->callApi($parameters);
return json_decode($response, true);
} | php | {
"resource": ""
} |
q262337 | Worker.start | test | public function start()
{
if (!$this->simulation) {
$sockets = [];
socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets);
$pid = getmypid();
$this->pid = $this->forkThread([$this, 'onWorkerStart'], [$sockets[1], $pid]);
$this->toChild = $sockets[0];
socket_set_nonblock($this->toChild);
}
} | php | {
"resource": ""
} |
q262338 | Worker.stop | test | public function stop($wait = false)
{
if ($this->simulation) {
$this->state = self::TERMINATED;
return true;
}
if (!is_dir('/proc/'.$this->pid))
return null;
$this->state = self::TERMINATING;
if (!posix_kill($this->pid, SIGTERM))
return false;
if ($wait) {
pcntl_waitpid($this->pid, $status);
$this->state = self::TERMINATED;
} else {
if (!is_dir('/proc/'.$this->pid))
$this->state = self::TERMINATED;
}
return true;
} | php | {
"resource": ""
} |
q262339 | Worker.kill | test | public function kill($wait = false)
{
if ($this->simulation) {
$this->state = self::TERMINATED;
return true;
}
if (!is_dir('/proc/'.$this->pid))
return null;
$this->state = self::TERMINATING;
if (!posix_kill($this->pid, SIGKILL))
return false;
if ($wait) {
pcntl_waitpid($this->pid, $status);
$this->state = self::TERMINATED;
} else {
if (!is_dir('/proc/'.$this->pid))
$this->state = self::TERMINATED;
}
return true;
} | php | {
"resource": ""
} |
q262340 | Worker.sendPayload | test | public function sendPayload($data)
{
// if not forked yet
if (!$this->simulation && $this->pid === null) {
$this->start();
}
$this->remainingPayloadsCounter++;
$this->state = self::RUNNING;
if ($this->simulation) {
$result = $this->sentPayloadsCounter++;
$this->simulationBuffer[$result] = $this->onPayload($data);
$this->state = self::IDLE;
return $result;
}
$data = serialize($data);
// write payload to socket
socket_write($this->toChild, pack('N', strlen($data)));
socket_write($this->toChild, $data);
return $this->sentPayloadsCounter++;
} | php | {
"resource": ""
} |
q262341 | Worker.onWorkerStart | test | protected function onWorkerStart($socket, $parentPid)
{
declare(ticks = 1);
// set signal handler
pcntl_signal(SIGTERM, [$this, 'onSigTerm']);
$this->toParent = $socket;
$this->parentPid = $parentPid;
socket_set_nonblock($this->toParent);
$i = 0;
while (!$this->termAccepted) {
// echo ($i++).' try'.PHP_EOL;
// sleep for sometime
if (strlen($msg_size_bytes = socket_read($this->toParent, 4)) != 4) {
usleep($this->checkMicroTime);
continue;
}
$data = unpack('N', $msg_size_bytes);
$msg_size = $data[1];
$msg = socket_read($this->toParent, $msg_size);
$data = unserialize($msg);
// echo '[Payload] Msg('.$msg_size.'): '.$msg.PHP_EOL;
// launch worker to do it's work
$result = call_user_func([$this, 'onPayload'], $data);
$data = serialize($result);
// write result to socket
socket_write($this->toParent, pack('N', strlen($data)));
// echo '[Finish] Msg('.strlen($data).'): '.$data.PHP_EOL;
socket_write($this->toParent, $data);
// send SIGUSR1 to parent to indicate that's we've finished
if ($this->useSignals)
posix_kill($this->parentPid, SIGUSR1);
}
socket_close($this->toParent);
// notify we ended
if ($this->useSignals)
posix_kill($this->parentPid, SIGUSR2);
} | php | {
"resource": ""
} |
q262342 | ForkingThread.forkThread | test | public function forkThread($callback, array $params = [])
{
$res = pcntl_fork();
if ($res < 0)
throw new Exception('Can\'t fork');
if ($res === 0) {
call_user_func_array($callback, $params);
exit;
} else {
return $res;
}
} | php | {
"resource": ""
} |
q262343 | SamlUtils.getAuthnRequest | test | public function getAuthnRequest(
$consumer_service_url,
$idp_destination,
$issuer,
$saml_crt,
$saml_key
) {
$authn_request = new AuthnRequest();
$authn_request
->setAssertionConsumerServiceURL($consumer_service_url)
->setProtocolBinding(SamlConstants::BINDING_SAML2_HTTP_POST)
->setID(Helper::generateID())
->setIssueInstant(new DateTime())
->setDestination($idp_destination)
->setIssuer(new Issuer($issuer));
$certificate = new X509Certificate();
$certificate->loadPem($saml_crt);
$private_key = KeyHelper::createPrivateKey($saml_key, '', false);
$authn_request->setSignature(new SignatureWriter($certificate, $private_key));
$serialization_context = new SerializationContext();
$authn_request->serialize($serialization_context->getDocument(), $serialization_context);
$binding_factory = new BindingFactory();
$redirect_binding = $binding_factory->create(SamlConstants::BINDING_SAML2_HTTP_REDIRECT);
$message_context = new MessageContext();
$message_context->setMessage($authn_request);
/** @var \Symfony\Component\HttpFoundation\RedirectResponse $http_response */
$http_response = $redirect_binding->send($message_context);
return $http_response->getTargetUrl();
} | php | {
"resource": ""
} |
q262344 | SamlUtils.parseSamlResponse | test | public function parseSamlResponse(array $payload)
{
$deserialization_context = new DeserializationContext();
$deserialization_context->getDocument()->loadXML(base64_decode($payload['SAMLResponse']));
$saml_response = new Response();
$saml_response->deserialize($deserialization_context->getDocument()->firstChild, $deserialization_context);
return $saml_response;
} | php | {
"resource": ""
} |
q262345 | Manager.getBinaries | test | public function getBinaries(callable $predicate = null)
{
$binaries = $this->binaries;
if ($predicate !== null) {
return array_filter($binaries, $predicate);
}
return $binaries;
} | php | {
"resource": ""
} |
q262346 | Manager.getPendingBinaries | test | public function getPendingBinaries()
{
return $this->getBinaries(function (BinaryInterface $binary) {
$exists = $binary->exists($this->getInstallPath());
$supported = $binary->isSupported();
return $supported && !$exists;
});
} | php | {
"resource": ""
} |
q262347 | Manager.update | test | public function update($binaryName = '')
{
if ($binaryName) {
$this->updateSingle($binaryName);
return;
}
foreach ($this->binaries as $binary) {
$binary->fetchAndSave($this->getInstallPath());
}
} | php | {
"resource": ""
} |
q262348 | Manager.updateSingle | test | public function updateSingle($binaryName)
{
if (! array_key_exists($binaryName, $this->binaries)) {
throw new RuntimeException("Binary named $binaryName does not exist");
}
$binary = $this->binaries[$binaryName];
$binary->fetchAndSave($this->getInstallPath());
} | php | {
"resource": ""
} |
q262349 | Manager.start | test | public function start($background = false, $port = 4444, array $args = [])
{
$selenium = $this->binaries['selenium'];
$this->assertStartConditions($selenium);
$process = $this->getSeleniumProcess();
$this->registerBinaries($process, $selenium);
if ($port != 4444) {
$process->addArg('-port', $port);
}
if (!empty($args)) {
$process->addArgs($args);
}
return $process->start($background);
} | php | {
"resource": ""
} |
q262350 | Manager.clean | test | public function clean()
{
$files = glob($this->getInstallPath() . '/*');
foreach ($files as $file) {
unlink($file);
}
} | php | {
"resource": ""
} |
q262351 | Manager.assertStartConditions | test | protected function assertStartConditions(SeleniumStandalone $selenium)
{
if (!$selenium->exists($this->getInstallPath())) {
throw new RuntimeException("Selenium Standalone binary not installed");
}
if (!$this->getSeleniumProcess()->isAvailable()) {
throw new RuntimeException('java is not available');
}
} | php | {
"resource": ""
} |
q262352 | Manager.registerBinaries | test | protected function registerBinaries(SeleniumProcessInterface $process, SeleniumStandalone $selenium)
{
$drivers = $this->getDrivers();
foreach ($drivers as $driver) {
$process->addBinary($driver, $this->getInstallPath());
}
$process->addBinary($selenium, $this->getInstallPath());
} | php | {
"resource": ""
} |
q262353 | BinaryHelper.createBinary | test | public function createBinary($name, $supported, $exists)
{
$binary = $this->prophet->prophesize('Peridot\WebDriverManager\Binary\BinaryInterface');
$binary->isSupported()->willReturn($supported);
$binary->getName()->willReturn($name);
$binary->exists(Argument::any())->willReturn($exists);
return $binary;
} | php | {
"resource": ""
} |
q262354 | LoginPolicy.getValidExternalUrlValue | test | private function getValidExternalUrlValue($url)
{
if ($url === null || (is_string($url) && filter_var($url, FILTER_VALIDATE_URL))) {
return $url;
}
throw new InvalidArgumentException('URL is not valid');
} | php | {
"resource": ""
} |
q262355 | ChromeDriver.getLinuxFileName | test | public function getLinuxFileName()
{
$file = "linux32";
$system = $this->resolver->getSystem();
if ($system->is64Bit()) {
$file = 'linux64';
}
return $file;
} | php | {
"resource": ""
} |
q262356 | CompressedBinary.save | test | public function save($directory)
{
if (empty($this->contents)) {
return false;
}
if ($this->exists($directory)) {
return true;
}
$compressedPath = $directory . DIRECTORY_SEPARATOR . $this->getOutputFileName();
$this->removeOldVersions($directory);
file_put_contents($compressedPath, $this->contents);
$extracted = $this->resolver->extract($compressedPath, $directory);
if ($extracted) {
chmod("$directory/{$this->getExtractedName()}", 0777);
}
return $extracted;
} | php | {
"resource": ""
} |
q262357 | StandardBinaryRequest.onNotification | test | public function onNotification($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max)
{
switch($notification_code) {
case STREAM_NOTIFY_PROGRESS:
$this->emit('progress', [$bytes_transferred]);
break;
case STREAM_NOTIFY_FILE_SIZE_IS:
$this->emit('request.start', [$this->url, $bytes_max]);
break;
}
} | php | {
"resource": ""
} |
q262358 | UpdateCommand.watchProgress | test | protected function watchProgress(OutputInterface $output)
{
$progress = new ProgressBar($output);
$progress->setFormat('%bar% (%percent%%)');
$this->manager->on('request.start', function ($url, $bytes) use ($progress, $output) {
$output->writeln('<comment>Downloading ' . basename($url) . '</comment>');
$progress->start($bytes);
});
$this->manager->on('progress', function ($transferred) use ($progress) {
$progress->setProgress($transferred);
});
$this->manager->on('complete', function () use ($progress, $output) {
$progress->finish();
$output->writeln('');
});
} | php | {
"resource": ""
} |
q262359 | UpdateCommand.getPreMessage | test | protected function getPreMessage($name)
{
$binaries = $this->manager->getBinaries();
$message = 'Ensuring binaries are up to date';
$isSingleUpdate = $name && array_key_exists($name, $binaries);
if (! $isSingleUpdate) {
return $message;
}
$binary = $binaries[$name];
return $binary->isSupported() ? "Updating {$binary->getName()}" : "{$binary->getName()} is not supported by your system";
} | php | {
"resource": ""
} |
q262360 | UpdateCommand.getPostMessage | test | protected function getPostMessage(array $pending, $name)
{
if ($name) {
$pending = array_filter($pending, function (BinaryInterface $binary) use ($name) {
return $binary->getName() === $name;
});
}
$count = array_reduce($pending, function ($r, BinaryInterface $binary) {
if ($binary->exists($this->manager->getInstallPath())) {
$r++;
}
return $r;
}, 0);
return $this->getResultString($count);
} | php | {
"resource": ""
} |
q262361 | Workflow.addPipe | test | protected function addPipe(AbstractPipe $pipe)
{
if ($pipe->getPosition() === self::PREPEND) {
array_unshift($this->pipeline, $pipe);
} else {
$this->pipeline[] = $pipe;
}
return $this;
} | php | {
"resource": ""
} |
q262362 | Workflow.convertItem | test | protected function convertItem($item, ConverterPipe $pipe)
{
$filterValue = $pipe->getFilterField() ? Vale::get($item, $pipe->getFilterField()) : $item;
if ($pipe->getFilter() === null || $pipe->getFilter()->filter($filterValue) === true) {
return $pipe->getConverter()->convert($item);
}
return $item;
} | php | {
"resource": ""
} |
q262363 | Workflow.convertItemValue | test | protected function convertItemValue($item, ConverterPipe $pipe)
{
$value = Vale::get($item, $pipe->getField());
$filterValue = $pipe->getFilterField() ? Vale::get($item, $pipe->getFilterField()) : $item;
if ($pipe->getFilter() === null || $pipe->getFilter()->filter($filterValue) === true) {
$item = Vale::set($item, $pipe->getField(), $pipe->getConverter()->convert($value));
}
return $item;
} | php | {
"resource": ""
} |
q262364 | Workflow.writeItem | test | protected function writeItem($item, WriterPipe $pipe)
{
if ($pipe->getFilter() === null || $pipe->getFilter()->filter($item) === true) {
$pipe->getWriter()->writeItem($item);
return true;
}
return false;
} | php | {
"resource": ""
} |
q262365 | ApplyAuthenticationMiddleware.getTransportFrom | test | protected function getTransportFrom(ServerRequestInterface $request)
{
if ($this->value_container instanceof RequestValueContainerInterface) {
$this->value_container->setRequest($request);
}
if ($this->value_container->hasValue()) {
return $this->value_container->getValue();
}
return null;
} | php | {
"resource": ""
} |
q262366 | PasswordStrengthValidator.validate | test | public function validate($password, PasswordPolicyInterface $policy)
{
if (!is_string($password)) {
throw new InvalidPasswordException('Password is not a string');
}
$password = trim($password);
if (empty($password)) {
throw new InvalidPasswordException('Password is empty');
}
$errors = 0;
if ($policy->getMinLength() && mb_strlen($password) < $policy->getMinLength()) {
$errors += PasswordStrengthValidatorInterface::TOO_SHORT;
}
if ($policy->requireNumbers() && !preg_match('#\d#', $password)) {
$errors += PasswordStrengthValidatorInterface::NO_NUMBERS;
}
if ($policy->requireMixedCase() && !(preg_match('/[A-Z]+/', $password) && preg_match('/[a-z]+/', $password))) {
$errors += PasswordStrengthValidatorInterface::NO_MIXED_CASE;
}
if ($policy->requireSymbols() && !preg_match('/[,.;:!$\\\\%^&~@#*\/]+/', $password)) {
$errors += PasswordStrengthValidatorInterface::NO_SYMBOLS;
}
if ($errors > 0) {
throw new InvalidPasswordException('Password is not strong enough', $errors);
}
return true;
} | php | {
"resource": ""
} |
q262367 | TaxonomyAttribute.getTaxonomy | test | public function getTaxonomy(EntityContract $entity)
{
return $this->getRelationManager($entity)->findOrCreateOrFail(['name' => $this->getTaxonomyName()])->getResource();
} | php | {
"resource": ""
} |
q262368 | TaxonomyAttribute.valid | test | public function valid(EntityContract $entity, $value)
{
if (!parent::valid($entity, $value)) {
return false;
}
return ($this->getTaxonomyName() !== null && $value->parent_id === $this->getTaxonomy($entity)->id) || $this->getTaxonomyName() === null;
} | php | {
"resource": ""
} |
q262369 | TaxonomyAttribute.getDescriptor | test | public function getDescriptor()
{
return [
'constraint' => [
'parent_id' => $this->getTaxonomyName() ? $this->getTaxonomy($this->getManager()->newEntity())->id : null,
],
];
} | php | {
"resource": ""
} |
q262370 | Util.getEnv | test | public static function getEnv(string $key, $valueDefault = null)
{
// uppers for nginx
$value = $_ENV[$key] ?? $_ENV[strtoupper($key)] ??
$_SERVER[$key] ?? $_SERVER[strtoupper($key)] ?? $valueDefault;
if ($value === null) {
if (false === ($value = getenv($key))) {
$value = $valueDefault;
} elseif (function_exists('apache_getenv') && false === ($value = apache_getenv($key))) {
$value = $valueDefault;
}
}
return $value;
} | php | {
"resource": ""
} |
q262371 | Util.getClientIp | test | public static function getClientIp(): ?string
{
$ip = null;
if (null != ($ip = self::getEnv('HTTP_X_FORWARDED_FOR'))) {
if (false !== strpos($ip, ',')) {
$ip = trim((string) end(explode(',', $ip)));
}
}
// all ok
elseif (null != ($ip = self::getEnv('HTTP_CLIENT_IP'))) {}
elseif (null != ($ip = self::getEnv('HTTP_X_REAL_IP'))) {}
elseif (null != ($ip = self::getEnv('REMOTE_ADDR_REAL'))) {}
elseif (null != ($ip = self::getEnv('REMOTE_ADDR'))) {}
return $ip;
} | php | {
"resource": ""
} |
q262372 | Util.getCurrentUrl | test | public static function getCurrentUrl(bool $withQuery = true): string
{
static $filter, $scheme, $host, $port;
if ($filter == null) {
$filter = function($input) {
// decode first @important
$input = rawurldecode($input);
// encode quotes and html tags
return html_encode(
// remove NUL-byte, ctrl-z, vertical tab
preg_replace('~[\x00\x1a\x0b]|%(?:00|1a|0b)~i', '', trim(
// slice at \n or \r
substr($input, 0, strcspn($input, "\n\r"))
))
);
};
[$scheme, $host, $port] = [
$_SERVER['REQUEST_SCHEME'], $_SERVER['SERVER_NAME'], $_SERVER['SERVER_PORT']
];
}
$path = $_SERVER['REQUEST_URI'];
$query = '';
if (strpos($path, '?')) {
[$path, $query] = explode('?', $path, 2);
}
$port = ($scheme != 'https' && $port != '80') ? ':'. $port : '';
$path = $filter($path);
if (strpos($path, '//') !== false) {
$path = preg_replace('~/+~', '/', $path);
}
$url = sprintf('%s://%s%s%s', $scheme, $host, $port, $path);
if ($withQuery && $query != '') {
$url .= '?'. $filter($query);
}
return $url;
} | php | {
"resource": ""
} |
q262373 | Util.unparseQueryString | test | public static function unparseQueryString(array $input, bool $decode = false,
string $ignoredKeys = null, bool $stripTags = true, bool $normalizeArrays = true): string
{
if ($ignoredKeys != '') {
$ignoredKeys = explode(',', $ignoredKeys);
foreach ($input as $key => $_) {
if (in_array($key, $ignoredKeys)) {
unset($input[$key]);
}
}
}
// fix skipped NULL values by http_build_query()
static $filter; if ($filter == null) {
$filter = function ($var) use (&$filter) {
foreach ($var as $key => $value) {
$var[$key] = is_array($value) ? $filter($value) : strval($value);
}
return $var;
};
}
$query = http_build_query($filter($input));
if ($decode) {
$query = urldecode($query);
}
if ($stripTags && strpos($query, '%3C')) {
$query = preg_replace('~%3C[\w]+(%2F)?%3E~ismU', '', $query);
}
if ($normalizeArrays && strpos($query, '%5D')) {
$query = preg_replace('~([\w\.\-]+)%5B([\w\.\-]+)%5D(=)?~iU', '\1[\2]\3', $query);
}
return trim($query);
} | php | {
"resource": ""
} |
q262374 | PropertyIssetTrait.__isset | test | public final function __isset(string $name)
{
if (!property_exists($this, $name)) {
throw new PropertyTraitException(sprintf('Property %s::$%s does not exist',
static::class, $name));
}
return ($this->{$name} !== null);
} | php | {
"resource": ""
} |
q262375 | GeoCode.lookup | test | public function lookup($sAddress = '')
{
$sAddress = trim($sAddress);
if (empty($sAddress)){
return null;
}
// Check caches; local cache first followed by DB cache
$oCache = $this->getCache($sAddress);
if (!empty($oCache)) {
return $oCache;
}
$oDb = Factory::service('Database');
$oDb->select('X(latlng) lat, Y(latlng) lng');
$oDb->where('address', $sAddress);
$oDb->limit(1);
$oResult = $oDb->get(self::DB_CACHE_TABLE)->row();
if (!empty($oResult)) {
$oLatLng = Factory::factory('LatLng', 'nails/module-geo-code');
$oLatLng->setAddress($sAddress);
$oLatLng->setLat($oResult->lat);
$oLatLng->setLng($oResult->lng);
} else {
$oLatLng = $this->oDriver->lookup($sAddress);
if (!($oLatLng instanceof \Nails\GeoCode\Result\LatLng)) {
throw new GeoCodeException(
'Geo Code Driver did not return a \Nails\GeoCode\Result\LatLng result',
3
);
}
$sLat = $oLatLng->getLat();
$sLng = $oLatLng->getLng();
// Save to the DB Cache
if (!empty($sLat) && !empty($sLng)) {
$oDb->set('address', $sAddress);
$oDb->set('latlng', 'POINT(' . $sLat . ', ' . $sLng . ')', false);
$oDb->set('created', 'NOW()', false);
$oDb->insert(self::DB_CACHE_TABLE);
}
}
$this->setCache($sAddress, $oLatLng);
return $oLatLng;
} | php | {
"resource": ""
} |
q262376 | ExtendedJsonConfig.doInclusions | test | protected function doInclusions(&$value, $key, string $baseDirectory)
{
if (!is_string($value)) {
return;
}
$matches = [];
if (preg_match(sprintf('/^\s*%1$s(?<action>include|extends)\:(?<var>[\w\-\.\,\s]+)%1$s\s*$/i', preg_quote(self::TAG)), $value, $matches) != 1) {
return;
}
try {
switch ($matches['action']) {
case 'include':
$value = $this->load($matches['var'], true, $baseDirectory);
break;
case 'extends':
$files = explode(',', $matches['var']);
$files = array_map('trim', $files);
$files = array_map(
function ($file) use ($baseDirectory) {
return $this->load($file, true, $baseDirectory);
},
$files);
$value = call_user_func_array('b_array_merge_recursive', $files);
break;
}
} catch (\Exception $e) {
throw new ConfigException(sprintf('Unable to do action of config line "%s"', $value), 0, $e);
}
} | php | {
"resource": ""
} |
q262377 | ExtendedJsonConfig.doActions | test | public function doActions(&$value)
{
if (!is_string($value)) {
return;
}
$matches = [];
if (preg_match(sprintf('/^\s*%1$s(?<action>[\w\-\.]+)\:(?<var>[\w\-\.\,\s]+)%1$s\s*$/i', preg_quote(self::TAG)), $value, $matches) != 1) {
return;
}
try {
if (!isset(self::$userDefinedActions[$matches['action']])) {
throw new ConfigException(sprintf('Unknown action "%s" in config file', $matches['action']));
}
$value = call_user_func_array(self::$userDefinedActions[$matches['action']],
[$matches['var'],
$this]);
} catch (ConfigException $e) {
throw $e;
} catch (\Exception $e) {
throw new ConfigException(sprintf('Unable to do action of config line "%s"', $value), 0, $e);
}
} | php | {
"resource": ""
} |
q262378 | FormShiftItemHandler.down | test | private static function down(array $array, int $item): array
{
if (\count($array) - 1 > $item) {
$b = \array_slice($array, 0, $item, true);
$b[] = $array[$item + 1];
$b[] = $array[$item];
$b += \array_slice($array, $item + 2, \count($array), true);
return $b;
}
return $array;
} | php | {
"resource": ""
} |
q262379 | FormShiftItemHandler.up | test | private static function up(array $array, int $item): array
{
if ($item > 0 && $item < \count($array)) {
$b = \array_slice($array, 0, $item - 1, true);
$b[] = $array[$item];
$b[] = $array[$item - 1];
$b += \array_slice($array, $item + 1, \count($array), true);
return $b;
}
return $array;
} | php | {
"resource": ""
} |
q262380 | FormService.updateFormRead | test | public function updateFormRead(string $formUuid): void
{
/**
* @var Form $aggregate
*/
$aggregate = $this->aggregateFactory->build($formUuid, Form::class);
// Build FormRead entity from Aggregate.
$formRead = $this->entityManager->getRepository(FormRead::class)->findOneByUuid($formUuid) ?? new FormRead();
$formRead->setVersion($aggregate->getStreamVersion());
$formRead->setUuid($formUuid);
$formData = json_decode(json_encode($aggregate), true);
$formRead->setPayload($formData);
$formRead->setTitle($aggregate->title);
$formRead->setEmail($aggregate->email);
$formRead->setEmailCC($aggregate->emailCC);
$formRead->setEmailBCC($aggregate->emailBCC);
$formRead->setSender($aggregate->sender);
$formRead->setTemplate($aggregate->template);
$formRead->setEmailTemplate($aggregate->emailTemplate);
$formRead->setEmailTemplateCopy($aggregate->emailTemplateCopy);
$formRead->setDeleted($aggregate->deleted);
$formRead->setHtml($aggregate->html);
$formRead->setSuccessText($aggregate->successText);
$formRead->setSaveSubmissions($aggregate->saveSubmissions);
$formRead->setCreated($aggregate->getCreated());
$formRead->setModified($aggregate->getModified());
// Persist FormRead entity.
$this->entityManager->persist($formRead);
$this->entityManager->flush();
} | php | {
"resource": ""
} |
q262381 | FormService.getField | test | private function getField(array $payload, array $data, string $propertyName)
{
$isField = false;
$payload = json_decode(json_encode($payload), true);
if ($payload['items'] && \is_array($payload['items']) && \count($payload['items']) > 0) {
foreach ($payload['items'] as $item) {
if (isset($item['data'][$propertyName]) && $item['data'][$propertyName]) {
$isField = $item['data']['name'];
}
}
}
return $isField ? $data[$isField] : null;
} | php | {
"resource": ""
} |
q262382 | FormBaseHandler.getMatching | test | private static function getMatching(array &$item, string $itemUuid, callable $callable = null, array &$collection)
{
// Return true if this item is the one we are looking for.
if (isset($item['uuid']) && $item['uuid'] === $itemUuid) {
if ($callable) {
$callable($item, $collection);
}
return $item;
}
// Look in child items.
if (isset($item['items']) && \is_array($item['items'])) {
foreach ($item['items'] as &$subItem) {
if ($c = self::getMatching($subItem, $itemUuid, $callable, $item['items'])) {
return $c;
}
}
}
return false;
} | php | {
"resource": ""
} |
q262383 | FormBaseHandler.onItem | test | public static function onItem(Form $aggregate, string $itemUuid, callable $callable): void
{
foreach ($aggregate->items as &$item) {
if ($c = self::getMatching($item, $itemUuid, $callable, $aggregate->items)) {
return;
}
}
} | php | {
"resource": ""
} |
q262384 | FormBaseHandler.getItem | test | public static function getItem(Form $aggregate, string $itemUuid)
{
foreach ($aggregate->items as &$item) {
if ($c = self::getMatching($item, $itemUuid, null, $aggregate->items)) {
return $c;
}
}
return null;
} | php | {
"resource": ""
} |
q262385 | AbstractConfig.replaceVariables | test | protected function replaceVariables(&$value)
{
if (!is_string($value)) {
return;
}
// Variables
$matches = [];
if (preg_match_all(sprintf('/%1$s(?<var>[\w\-\.\,\s]+)%1$s/i', preg_quote(self::TAG)), $value, $matches, PREG_SET_ORDER) == 0) {
return;
}
foreach ($matches as $match) {
// Is variable ?
if (is_null($subValue = $this->getVariable($match['var']))) {
$subValue = $this->get($match['var']);
}
// Booleans
if ($subValue === true) {
$subValue = 'true';
}
if ($subValue === false) {
$subValue = 'false';
}
$value = str_replace(sprintf('%2$s%1$s%2$s', $match['var'], self::TAG), $subValue, $value);
}
if (in_array($value, ['true', 'false'], true)) {
$value = $value == 'true';
} else {
if (filter_var($value, FILTER_VALIDATE_INT) !== false) {
$value = intval($value);
} else {
if (filter_var($value, FILTER_VALIDATE_FLOAT) !== false) {
$value = floatval($value);
}
}
}
$this->replaceVariables($value);
} | php | {
"resource": ""
} |
q262386 | JsonConfig.loadJson | test | protected function loadJson(string $json): array
{
$json = preg_replace('#^\s*//.*$\v?#mx', '', $json);
$configuration = json_decode($json, true);
if (!is_array($configuration)) {
throw new ConfigException('Not a valid JSON data');
}
return $configuration;
} | php | {
"resource": ""
} |
q262387 | JsonConfig.loadUrl | test | protected function loadUrl(string $jsonFile): array
{
//Get real path of file
if (($fileName = realpath($jsonFile)) === false) {
throw new NotFoundException(sprintf('File "%s" not found', $jsonFile));
}
// Read file
if (($json = @file_get_contents($fileName)) === false) {
throw new ConfigException(sprintf('Unable to load configuration file "%s"', $fileName));
}
try {
return $this->loadJson($json);
} catch (ConfigException $e) {
throw new ConfigException(sprintf('Not a valid JSON data for file "%s"', $fileName));
}
} | php | {
"resource": ""
} |
q262388 | LatLng.setLatLng | test | public function setLatLng($sLat, $sLng)
{
$this->setLat($sLat);
$this->setLng($sLng);
return $this;
} | php | {
"resource": ""
} |
q262389 | LatLng.getLatLng | test | public function getLatLng()
{
$oLatLng = new \stdClass();
$oLatLng->lat = $this->sLat;
$oLatLng->lng = $this->sLng;
return $oLatLng;
} | php | {
"resource": ""
} |
q262390 | FormController.errorResponse | test | public function errorResponse(string $formUuid = null)
{
$messages = $this->messageBus->getMessagesJson();
if ($formUuid) {
foreach ($messages as $message) {
$this->addFlash(
'warning',
$message['message']
);
}
return $this->redirectToForm($formUuid);
}
return new JsonResponse($messages);
} | php | {
"resource": ""
} |
q262391 | FormController.redirectToForm | test | private function redirectToForm(string $formUuid): Response
{
/** @var FormRead|null $formRead */
$formRead = $this->entityManager->getRepository(FormRead::class)->findOneBy([
'uuid' => $formUuid,
]);
if ($formRead) {
return $this->redirectToRoute('forms_edit_aggregate', [
'id' => $formRead->getId(),
]);
}
return $this->redirect('/admin');
} | php | {
"resource": ""
} |
q262392 | FormController.createFormAggregate | test | public function createFormAggregate(Request $request)
{
/** @var \Symfony\Component\Security\Core\User\UserInterface $user */
$user = $this->getUser();
$form = $this->createForm(FormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$aggregateUuid = Uuid::uuid1()->toString();
// Execute Command.
$success = false;
$this->commandBus->dispatch(new FormCreateCommand($user->getId(), Uuid::uuid1()->toString(), $aggregateUuid, 0, $data, function ($commandBus, $event) use (&$success) {
// Callback.
$success = true;
}));
if ($success) {
$this->addFlash(
'success',
'Form created'
);
return $this->redirectToForm($aggregateUuid);
}
return $this->errorResponse($aggregateUuid);
}
return $this->render('@forms/Form/form.html.twig', [
'title' => 'Add Form',
'form' => $form->createView(),
]);
} | php | {
"resource": ""
} |
q262393 | FormController.formRemoveItem | test | public function formRemoveItem(string $formUuid, int $onVersion, string $itemUuid)
{
/** @var \Symfony\Component\Security\Core\User\UserInterface $user */
$user = $this->getUser();
$success = false;
$this->commandBus->dispatch(new FormRemoveItemCommand($user->getId(), Uuid::uuid1()->toString(), $formUuid, $onVersion, [
'uuid' => $itemUuid,
], function ($commandBus, $event) use (&$success) {
// Callback.
$success = true;
}));
if ($success) {
$this->addFlash(
'success',
$this->translator->trans('Field deleted')
);
return $this->redirectToForm($formUuid);
}
return $this->errorResponse($formUuid);
} | php | {
"resource": ""
} |
q262394 | PluginInstaller.checkAutoloadDump | test | public static function checkAutoloadDump(\Composer\Composer $composer)
{
if (static::$useAutoloadDump === null) {
static::$useAutoloadDump = false;
$rootPackage = static::getRootPackage($composer);
if (!$rootPackage || ($rootPackage->getType() !== 'project')) {
return false;
}
$rootPackageRequires = $rootPackage->getRequires();
if (!isset($rootPackageRequires[static::PACKAGE_NAME])) {
return false;
}
$scripts = $rootPackage->getScripts();
$callback = get_called_class() . '::postAutoloadDump';
if (!isset($scripts['post-autoload-dump']) || !in_array($callback, $scripts['post-autoload-dump'])) {
return false;
}
static::$useAutoloadDump = true;
}
return static::$useAutoloadDump;
} | php | {
"resource": ""
} |
q262395 | PluginInstaller.getPluginClassNames | test | public static function getPluginClassNames(
\Composer\Package\PackageInterface $package,
\Composer\Package\PackageInterface $rootPackage = null
) {
$packageType = $package->getType();
$packagePrettyName = $package->getPrettyName();
$packageName = $package->getName();
$classNames = array();
// 1. root package
$rootPackageExtra = $rootPackage ? $rootPackage->getExtra() : null;
if (!empty($rootPackageExtra[$packageType])) {
$classNames = (array) $this->mapRootExtra($rootPackageExtra[$packageType], $packagePrettyName);
}
// 2. package
if (!$classNames) {
$packageExtra = $package->getExtra();
if (!empty($packageExtra[$packageType])) {
$classNames = (array) $packageExtra[$packageType];
}
}
// 3. guess by installer name
if (!$classNames) {
$installName = static::getInstallName($package, $rootPackage);
$classNames = array($installName);
}
return $classNames;
} | php | {
"resource": ""
} |
q262396 | PluginInstaller.getInstallName | test | public static function getInstallName(
\Composer\Package\PackageInterface $package,
\Composer\Package\PackageInterface $rootPackage = null
) {
$packagePrettyName = $package->getPrettyName();
$packageName = $package->getName();
$installName = null;
$rootPackageExtra = $rootPackage ? $rootPackage->getExtra() : null;
if (!empty($rootPackageExtra['installer-name'])) {
$installName = $this->mapRootExtra($rootPackageExtra['installer-name'], $packagePrettyName);
}
if (!$installName) {
$packageExtra = $package->getExtra();
if (!empty($packageExtra['installer-name'])) {
$installName = $packageExtra['installer-name'];
}
}
return $installName ?: static::guessInstallName($packageName);
} | php | {
"resource": ""
} |
q262397 | PluginInstaller.guessInstallName | test | protected static function guessInstallName($packageName)
{
$name = $packageName;
if (strpos($packageName, '/') !== false) {
list(, $name) = explode('/', $packageName);
}
$name = preg_replace('/[\.\-_]+(?>plugin|theme)$/u', '', $name);
$name = preg_replace_callback(
'/(?>^[\.\-_]*|[\.\-_]+)(.)/u',
function ($matches) {
return strtoupper($matches[1]);
},
$name
);
return $name;
} | php | {
"resource": ""
} |
q262398 | PluginInstaller.mapRootExtra | test | protected static function mapRootExtra(array $packageExtra, $packagePrettyName)
{
if (isset($packageExtra[$packagePrettyName])) {
return $packageExtra[$packagePrettyName];
}
if (strpos($packagePrettyName, '/') !== false) {
list($vendor, $name) = explode('/', $packagePrettyName);
} else {
$vendor = '';
$name = $packagePrettyName;
}
foreach ($packageExtra as $key => $value) {
if ((substr($key, 0, 5) === 'name:') && (substr($key, 5) === $name)) {
return $value;
} elseif ((substr($key, 0, 7) === 'vendor:') && (substr($key, 7) === $vendor)) {
return $value;
}
}
return null;
} | php | {
"resource": ""
} |
q262399 | PluginInstaller.writePluginConfig | test | public static function writePluginConfig($pluginConfig, array $plugins, array $pluginClassNames)
{
$data = array();
foreach ($plugins as $pluginName => $installerName) {
// see https://github.com/composer/composer/blob/1.0.0/src/Composer/Command/InitCommand.php#L206-L210
if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $pluginName)) {
throw new \InvalidArgumentException(
"The package name '" . $pluginName . "' is invalid, it must be lowercase and have a vendor name, "
. "a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+"
);
}
$data[] = sprintf(" '%s' => array(", $pluginName);
if (!preg_match('{^[a-zA-Z0-9_.-]+$}', $installerName)) {
throw new \InvalidArgumentException(
"The installer name '" . $installerName . "' is invalid, "
. "it must be alphanumeric, matching: [a-zA-Z0-9_.-]+"
);
}
$data[] = sprintf(" 'installerName' => '%s',", $installerName);
if (isset($pluginClassNames[$pluginName])) {
$data[] = sprintf(" 'classNames' => array(");
foreach ($pluginClassNames[$pluginName] as $className) {
// see https://secure.php.net/manual/en/language.oop5.basic.php
if (!preg_match('{^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$}', $className)) {
throw new \InvalidArgumentException(
"The plugin class name '" . $className . "' is no valid PHP class name"
);
}
$data[] = sprintf(" '%s',", $className);
}
$data[] = " ),";
}
$data[] = " ),";
}
$contents = <<<'PHP'
<?php
// %s @generated by %s
return array(
%s
);
PHP;
$contents = sprintf(
$contents,
basename($pluginConfig),
static::PACKAGE_NAME,
implode("\n", $data)
);
file_put_contents($pluginConfig, $contents);
} | 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.