_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q257000
Downloader.getVersion
test
public function getVersion(): ?string { if (!$this->version) { $this->version = self::getLatestVersion(); } return $this->version; }
php
{ "resource": "" }
q257001
Downloader.getFileUrl
test
public function getFileUrl(): string { $version = $this->getVersion(); Assert::that($version, 'Invalid version (expected format is X.Y.Z)') ->notEmpty() ->regex('/^\d+\.\d+\.[\da-z\-]+$/i'); $versionParts = explode('.', $version); $devVersion = ''; if (preg_match('/(\d+)-([[:alnum:]]+)/', $versionParts[2], $matches)) { $devVersion = $matches[2]; } $fileUrl = self::$storageUrl . '/' . $versionParts[0] . '.' . $versionParts[1] . (!empty($devVersion) ? '-' . $devVersion : '') . '/' . $this->getFileName(); return $fileUrl; }
php
{ "resource": "" }
q257002
Downloader.download
test
public function download(): int { $targetPath = $this->getFilePath(); if (!is_dir(dirname($targetPath))) { mkdir(dirname($targetPath), 0777, true); } $fileUrl = $this->getFileUrl(); $fp = @fopen($fileUrl, 'rb'); $responseHeaders = get_headers($fileUrl); if (mb_strpos($responseHeaders[0], '200 OK') === false) { throw new \RuntimeException(sprintf('Error downloading file "%s" (%s)', $fileUrl, $responseHeaders[0])); } $downloadedSize = file_put_contents($targetPath, $fp); // @codeCoverageIgnoreStart if (!$downloadedSize) { throw new \RuntimeException(sprintf('Error saving file to path "%s"', $targetPath)); } // @codeCoverageIgnoreEnd return $downloadedSize; }
php
{ "resource": "" }
q257003
Select2.selectByVisiblePartialText
test
public function selectByVisiblePartialText($text): void { $this->openDropdownOptions(); $this->log('Sending keys to select2: %s', $text); $inputSelector = WebDriverBy::cssSelector( $this->isMultiple() ? $this->select2Selector . ' input' : '#select2-drop input' ); // Insert searched term into Select2 generated input $this->tc->wd ->findElement($inputSelector) ->sendKeys($text); // Wait until result are rendered (or maybe loaded with ajax) $firstResult = $this->tc->wd->wait()->until( WebDriverExpectedCondition::presenceOfElementLocated( WebDriverBy::cssSelector('.select2-drop .select2-result.select2-highlighted') ) ); $this->log('Dropdown detected, selecting the first result: %s', $firstResult->getText()); // Select first item in results $firstResult->click(); }
php
{ "resource": "" }
q257004
Legacy.saveWithName
test
public function saveWithName($data, string $legacyName): void { $filename = $this->getLegacyFullPath($legacyName); $this->log('Saving data as Legacy "%s" to file "%s"', $legacyName, $filename); $this->debug('Legacy data: %s', $this->getPrintableValue($data)); if (@file_put_contents($filename, serialize($data)) === false) { throw new LegacyException('Cannot save Legacy to file ' . $filename); } }
php
{ "resource": "" }
q257005
Legacy.save
test
public function save($data, string $type = self::LEGACY_TYPE_CASE): void { $this->saveWithName($data, $this->getLegacyName($type)); }
php
{ "resource": "" }
q257006
Legacy.load
test
public function load(string $type = self::LEGACY_TYPE_CASE) { return $this->loadWithName($this->getLegacyName($type)); }
php
{ "resource": "" }
q257007
Legacy.loadWithName
test
public function loadWithName(string $legacyName) { $filename = $this->getLegacyFullPath($legacyName); $this->log('Reading Legacy "%s" from file "%s"', $legacyName, $filename); $data = @file_get_contents($filename); if ($data === false) { throw new LegacyException('Cannot read Legacy file ' . $filename); } $legacy = unserialize($data); if ($legacy === false) { throw new LegacyException('Cannot parse Legacy from file ' . $filename); } $this->debug('Legacy data: %s', $this->getPrintableValue($legacy)); return $legacy; }
php
{ "resource": "" }
q257008
SeleniumServerAdapter.isAccessible
test
public function isAccessible(): bool { // Check connection to server is possible $seleniumConnection = @fsockopen( $this->serverUrlParts['host'], $this->serverUrlParts['port'], $connectionErrorNo, $connectionError, 5 ); if (!is_resource($seleniumConnection)) { $this->lastError = $connectionError ?? 'unknown connection error'; return false; } fclose($seleniumConnection); return true; }
php
{ "resource": "" }
q257009
SeleniumServerAdapter.isSeleniumServer
test
public function isSeleniumServer(): bool { // Check server properly responds to http requests $context = stream_context_create(['http' => ['ignore_errors' => true, 'timeout' => 5]]); $responseData = @file_get_contents($this->getServerUrl() . self::STATUS_ENDPOINT, false, $context); if (!$responseData) { $this->lastError = 'error reading server response'; return false; } $decodedData = json_decode($responseData); if (!$decodedData) { $this->lastError = 'error parsing server JSON response (' . json_last_error_msg() . ')'; return false; } $this->cloudService = $this->detectCloudServiceByStatus($decodedData); return true; }
php
{ "resource": "" }
q257010
SeleniumServerAdapter.getCloudService
test
public function getCloudService(): string { // If cloud service value is not yet initialized, attempt to connect to the server first if ($this->cloudService === null) { if (!$this->isSeleniumServer()) { throw new \RuntimeException(sprintf('Unable to connect to remote server: %s', $this->getLastError())); } } return $this->cloudService; }
php
{ "resource": "" }
q257011
SeleniumServerAdapter.guessPort
test
protected function guessPort(string $host, string $scheme): int { if ($scheme === 'https') { return self::DEFAULT_PORT_CLOUD_SERVICE_HTTPS; } foreach (['saucelabs.com', 'browserstack.com', 'testingbot.com'] as $knownCloudHost) { if (mb_strpos($host, $knownCloudHost) !== false) { return self::DEFAULT_PORT_CLOUD_SERVICE; } } return self::DEFAULT_PORT; }
php
{ "resource": "" }
q257012
SeleniumServerAdapter.detectCloudServiceByStatus
test
private function detectCloudServiceByStatus($responseData): string { if (isset($responseData->value, $responseData->value->build, $responseData->value->build->version)) { if ($responseData->value->build->version === 'Sauce Labs') { return self::CLOUD_SERVICE_SAUCELABS; } elseif ($responseData->value->build->version === 'TestingBot') { return self::CLOUD_SERVICE_TESTINGBOT; } elseif (!isset($responseData->class) && !isset($responseData->value->ready)) { return self::CLOUD_SERVICE_BROWSERSTACK; } } return ''; }
php
{ "resource": "" }
q257013
ProcessSetCreator.buildProcess
test
protected function buildProcess(string $fileName, array $phpunitArgs = []): Process { $capabilities = (new KeyValueCapabilityOptionsParser()) ->parse($this->input->getOption(RunCommand::OPTION_CAPABILITY)); $env = [ 'BROWSER_NAME' => $this->input->getArgument(RunCommand::ARGUMENT_BROWSER), 'ENV' => mb_strtolower($this->input->getArgument(RunCommand::ARGUMENT_ENVIRONMENT)), 'CAPABILITY' => json_encode($capabilities), 'CAPABILITIES_RESOLVER' => $this->config[ConfigOptions::CAPABILITIES_RESOLVER], 'SERVER_URL' => $this->input->getOption(RunCommand::OPTION_SERVER_URL), 'LOGS_DIR' => $this->config[ConfigOptions::LOGS_DIR], 'DEBUG' => $this->output->isDebug() ? '1' : '0', ]; $dispatcher = $this->command->getDispatcher(); $dispatcher->dispatch( CommandEvents::RUN_TESTS_PROCESS, $processEvent = new RunTestsProcessEvent( $this->command, $this->input, $this->output, $env, $phpunitArgs ) ); $phpunitExecutable = realpath(__DIR__ . '/../../bin/phpunit-steward'); $commandLine = array_merge([PHP_BINARY, $phpunitExecutable], $processEvent->getArgs(), [$fileName]); return new Process($commandLine, STEWARD_BASE_DIR, $processEvent->getEnvironmentVars(), null, 3600); }
php
{ "resource": "" }
q257014
ProcessSetCreator.getExcludingGroups
test
private function getExcludingGroups(array $excludeGroups, array $annotations): array { $excludingGroups = []; if (!empty($excludeGroups) && array_key_exists('group', $annotations)) { if (!empty(array_intersect($excludeGroups, $annotations['group']))) { $excludingGroups = array_intersect($excludeGroups, $annotations['group']); } } return $excludingGroups; }
php
{ "resource": "" }
q257015
SnapshotListener.takeSnapshot
test
protected function takeSnapshot(AbstractTestCase $test): void { if (!$test->wd instanceof RemoteWebDriver) { $test->appendTestLog('[WARN] WebDriver instance not found, cannot take snapshot.'); return; } $savePath = ConfigProvider::getInstance()->logsDir . DIRECTORY_SEPARATOR; $testIdentifier = $this->assembleTestIdentifier($test); ob_start(); $outputBufferClosed = false; try { $currentUrl = $test->wd->getCurrentURL(); // Save PNG screenshot $screenshotPath = $savePath . $testIdentifier . '.png'; $test->wd->takeScreenshot($screenshotPath); // Save HTML snapshot of page $htmlPath = $savePath . $testIdentifier . '.html'; file_put_contents($htmlPath, $test->wd->getPageSource()); $bufferedOutput = ob_get_clean(); $outputBufferClosed = true; $test->appendFormattedTestLog($bufferedOutput); $test->appendTestLog(''); $test->appendTestLog('[WARN] Test failed on page "%s", taking page snapshots:', $currentUrl); $test->appendTestLog('Screenshot: "%s"', $this->getSnapshotUrl($screenshotPath)); $test->appendTestLog('HTML snapshot: "%s"', $this->getSnapshotUrl($htmlPath)); $test->appendTestLog(''); } catch (WebDriverException $e) { $test->appendTestLog('[WARN] Error taking page snapshot, perhaps browser is not accessible?'); return; } finally { if (!$outputBufferClosed) { $test->appendFormattedTestLog(ob_get_clean()); } } }
php
{ "resource": "" }
q257016
SnapshotListener.getSnapshotUrl
test
protected function getSnapshotUrl(string $path): string { if (getenv('JENKINS_URL') && getenv('BUILD_URL') && getenv('WORKSPACE')) { $realPath = realpath($path); if ($realPath) { // from absolute path, remove workspace $path = str_replace(getenv('WORKSPACE'), '', $realPath); // prepend url to artifact $path = getenv('BUILD_URL') . 'artifact' . DIRECTORY_SEPARATOR . $path; } } return $path; }
php
{ "resource": "" }
q257017
ListenerInstantiator.instantiate
test
public function instantiate(EventDispatcher $dispatcher, string $dirToSearchForListeners): void { $listeners = $this->searchListeners($dirToSearchForListeners); foreach ($listeners as $listener) { $r = new \ReflectionClass($listener); if ($r->implementsInterface('Symfony\\Component\\EventDispatcher\\EventSubscriberInterface') && !$r->isAbstract() ) { /** @var EventSubscriberInterface $listenerInstance */ $listenerInstance = $r->newInstanceWithoutConstructor(); $dispatcher->addSubscriber($listenerInstance); } } }
php
{ "resource": "" }
q257018
XmlPublisher.getFilePath
test
public function getFilePath(): string { if (!$this->fileDir) { $this->fileDir = ConfigProvider::getInstance()->logsDir; } return $this->fileDir . '/' . $this->fileName; }
php
{ "resource": "" }
q257019
XmlPublisher.quoteXpathAttribute
test
protected function quoteXpathAttribute(string $input): string { if (mb_strpos($input, '\'') === false) { // Selector does not contain single quotes return "'$input'"; // Encapsulate with double quotes } if (mb_strpos($input, '"') === false) { // Selector contain single quotes but not double quotes return "\"$input\""; // Encapsulate with single quotes } // When both single and double quotes are contained, escape each part individually and concat() all parts return "concat('" . strtr($input, ['\'' => '\', "\'", \'']) . "')"; }
php
{ "resource": "" }
q257020
MaxTotalDelayStrategy.optimize
test
public function optimize(OutTree $tree): array { // get root node of the tree $root = $tree->getVertexRoot(); // get all root descendants vertices (without the root vertex itself) $children = $tree->getVerticesDescendant($root); // for each vertex (process) get maximum total weight of its subtree (longest distance) $subTreeMaxDistances = []; /** @var Vertex $childVertex */ foreach ($children as $childVertex) { $alg = new Dijkstra($childVertex); // get map with distances to all linked reachable vertexes $distanceMap = $alg->getDistanceMap(); // save the longest distance $subTreeMaxDistances[$childVertex->getId()] = $distanceMap ? max($distanceMap) : 0; } return $subTreeMaxDistances; }
php
{ "resource": "" }
q257021
KeyValueCapabilityOptionsParser.castToGuessedDataType
test
private function castToGuessedDataType(string $value) { $stringValueWithoutQuotes = $this->removeEncapsulatingQuotes($value); if ($stringValueWithoutQuotes !== null) { return $stringValueWithoutQuotes; } $intValue = filter_var($value, FILTER_VALIDATE_INT, []); if ($intValue !== false) { return $intValue; } $floatValue = filter_var($value, FILTER_VALIDATE_FLOAT, []); if ($floatValue !== false) { return $floatValue; } $boolValue = filter_var($value, FILTER_VALIDATE_BOOLEAN, ['flags' => FILTER_NULL_ON_FAILURE]); if ($boolValue !== null) { return $boolValue; } return $value; }
php
{ "resource": "" }
q257022
ProcessWrapper.checkProcessTimeout
test
public function checkProcessTimeout(): ?string { try { $this->getProcess()->checkTimeout(); } catch (ProcessTimedOutException $e) { $this->setStatus(self::PROCESS_STATUS_DONE); return sprintf( 'Process for class "%s" exceeded the timeout of %d seconds and was killed.', $this->getClassName(), $e->getExceededTimeout() ); } return ''; }
php
{ "resource": "" }
q257023
ProcessWrapper.resolveResult
test
private function resolveResult(): string { $exitCode = $this->getProcess()->getExitCode(); // If the process was not even started, mark its result as failed if ($exitCode === null) { return self::PROCESS_RESULT_FAILED; } switch ($exitCode) { case TestRunner::SUCCESS_EXIT: // all tests passed $result = self::PROCESS_RESULT_PASSED; // for passed process save just the status and result; end time was saved by TestStatusListener break; case 15: // Process killed because of timeout, or case 9: // Process terminated because of timeout $result = self::PROCESS_RESULT_FATAL; break; case 255: // PHP fatal error $result = self::PROCESS_RESULT_FATAL; break; case TestRunner::EXCEPTION_EXIT: // exception thrown from phpunit case TestRunner::FAILURE_EXIT: // some test failed default: $result = self::PROCESS_RESULT_FAILED; break; } return $result; }
php
{ "resource": "" }
q257024
TimelineDataBuilder.getExecutors
test
private function getExecutors(): array { $testElements = $this->xml->xpath('//testcase/test[@status="done"]'); $hasTestWithoutExecutor = false; $executors = []; foreach ($testElements as $testElement) { $executorValue = (string) $testElement['executor']; if (!empty($executorValue)) { $executors[] = $executorValue; } else { $hasTestWithoutExecutor = true; } } $executors = array_unique($executors); // sort and reindex sort($executors); // use executors index as a value and executor name as a key $executors = array_flip($executors); if ($hasTestWithoutExecutor) { $executors['unknown'] = 'unknown'; } return $executors; }
php
{ "resource": "" }
q257025
CapabilitiesResolver.setupCiCapabilities
test
protected function setupCiCapabilities( DesiredCapabilities $capabilities, AbstractTestCase $test ): DesiredCapabilities { $ci = $this->ciDetector->detect(); $capabilities->setCapability( 'build', $this->config->env . '-' . $ci->getBuildNumber() ); $capabilities->setCapability( 'tags', [$this->config->env, $ci->getCiName(), get_class($test)] ); return $capabilities; }
php
{ "resource": "" }
q257026
ConfigProvider.setCustomConfigurationOptions
test
public function setCustomConfigurationOptions(array $customConfigurationOptions): void { if ($this->config !== null) { throw new \RuntimeException( 'Custom configuration options can be set only before initialization of configuration' ); } $this->customConfigurationOptions = $customConfigurationOptions; }
php
{ "resource": "" }
q257027
ConfigProvider.retrieveConfigurationValues
test
private function retrieveConfigurationValues(array $options): array { $outputValues = []; foreach ($options as $option) { $value = getenv($option); // value was not retrieved => fail if ($value === false) { throw new \RuntimeException(sprintf('%s environment variable must be defined', $option)); } $outputValues[Inflector::camelize(mb_strtolower($option))] = $value; } return $outputValues; }
php
{ "resource": "" }
q257028
ExecutionLoop.dequeueProcessesWithoutDelay
test
protected function dequeueProcessesWithoutDelay(): void { $queuedProcesses = $this->processSet->get(ProcessWrapper::PROCESS_STATUS_QUEUED); foreach ($queuedProcesses as $className => $processWrapper) { if ($processWrapper->isDelayed()) { $this->io->writeln( sprintf( 'Testcase "%s" is queued to be run %01.1f minutes after testcase "%s" is finished', $className, $processWrapper->getDelayMinutes(), $processWrapper->getDelayAfter() ), OutputInterface::VERBOSITY_DEBUG ); } elseif ($this->parallelLimitReached()) { $this->io->writeln( sprintf('Max parallel limit reached, testcase "%s" is queued', $className), OutputInterface::VERBOSITY_QUIET ); } else { $this->io->writeln( sprintf('Testcase "%s" is prepared to be run', $className), OutputInterface::VERBOSITY_DEBUG ); $processWrapper->setStatus(ProcessWrapper::PROCESS_STATUS_PREPARED); } } }
php
{ "resource": "" }
q257029
ExecutionLoop.flushProcessOutput
test
protected function flushProcessOutput(ProcessWrapper $processWrapper): void { $this->io->output( $processWrapper->getProcess()->getIncrementalOutput(), $processWrapper->getClassName() ); $this->io->errorOutput( $processWrapper->getProcess()->getIncrementalErrorOutput(), $processWrapper->getClassName() ); }
php
{ "resource": "" }
q257030
Favoriteability.favorite
test
public function favorite($class) { return $this->favorites()->where('favoriteable_type', $class)->with('favoriteable')->get()->mapWithKeys(function ($item) { return [$item['favoriteable']->id=>$item['favoriteable']]; }); }
php
{ "resource": "" }
q257031
MergeHTMLReportsTask.countSummary
test
private function countSummary($dstFile){ $tests = (new \DOMXPath($dstFile))->query("//table/tr[contains(@class,'scenarioRow')]"); foreach($tests as $test){ $class = str_replace('scenarioRow ', '', $test->getAttribute('class')); switch($class){ case 'scenarioSuccess': $this->countSuccess += 0.5; break; case 'scenarioFailed': $this->countFailed += 0.5; break; case 'scenarioSkipped': $this->countSkipped += 0.5; break; case 'scenarioIncomplete': $this->countIncomplete += 0.5; break; } } }
php
{ "resource": "" }
q257032
MergeHTMLReportsTask.updateSummaryTable
test
private function updateSummaryTable($dstFile){ $dstFile = new \DOMXPath($dstFile); $pathFor = function ($type) { return "//div[@id='stepContainerSummary']//td[@class='$type']";}; $dstFile->query($pathFor('scenarioSuccessValue'))->item(0)->nodeValue = $this->countSuccess; $dstFile->query($pathFor('scenarioFailedValue'))->item(0)->nodeValue = $this->countFailed; $dstFile->query($pathFor('scenarioSkippedValue'))->item(0)->nodeValue = $this->countSkipped; $dstFile->query($pathFor('scenarioIncompleteValue'))->item(0)->nodeValue = $this->countIncomplete; }
php
{ "resource": "" }
q257033
MergeHTMLReportsTask.moveSummaryTable
test
private function moveSummaryTable($dstFile,$node){ $summaryTable = (new \DOMXPath($dstFile))->query("//div[@id='stepContainerSummary']") ->item(0)->parentNode->parentNode; $node->appendChild($dstFile->importNode($summaryTable,true)); }
php
{ "resource": "" }
q257034
MergeHTMLReportsTask.updateButtons
test
private function updateButtons($dstFile){ $nodes = (new \DOMXPath($dstFile))->query("//div[@class='layout']/table/tr[contains(@class, 'scenarioRow')]"); for($i=2;$i<$nodes->length;$i+=2){ $n = $i/2 + 1; $p = $nodes->item($i)->childNodes->item(1)->childNodes->item(1); $table = $nodes->item($i+1)->childNodes->item(1)->childNodes->item(1); $p->setAttribute('onclick',"showHide('$n', this)"); $table->setAttribute('id',"stepContainer".$n); } }
php
{ "resource": "" }
q257035
Favoriteable.addFavorite
test
public function addFavorite($user_id = null) { $favorite = new Favorite(['user_id' => ($user_id) ? $user_id : Auth::id()]); $this->favorites()->save($favorite); }
php
{ "resource": "" }
q257036
Favoriteable.removeFavorite
test
public function removeFavorite($user_id = null) { $this->favorites()->where('user_id', ($user_id) ? $user_id : Auth::id())->delete(); }
php
{ "resource": "" }
q257037
Favoriteable.toggleFavorite
test
public function toggleFavorite($user_id = null) { $this->isFavorited($user_id) ? $this->removeFavorite($user_id) : $this->addFavorite($user_id) ; }
php
{ "resource": "" }
q257038
Favoriteable.isFavorited
test
public function isFavorited($user_id = null) { return $this->favorites()->where('user_id', ($user_id) ? $user_id : Auth::id())->exists(); }
php
{ "resource": "" }
q257039
Favoriteable.favoritedBy
test
public function favoritedBy() { return $this->favorites()->with('user')->get()->mapWithKeys(function ($item) { return [$item['user']->id => $item['user']]; }); }
php
{ "resource": "" }
q257040
Generator.getPermissions
test
public function getPermissions() { $permissions = [ $this->manage_permission ]; if ($this->create) { $permissions[] = $this->create_permission; $permissions[] = $this->store_permission; } if ($this->edit) { $permissions[] = $this->edit_permission; $permissions[] = $this->update_permission; } if ($this->delete) { $permissions[] = $this->delete_permission; } return $permissions; }
php
{ "resource": "" }
q257041
Generator.insertToLanguageFiles
test
public function insertToLanguageFiles() { //Model singular version $model_singular = Str::singular($this->originalName); //Model Plural version $model_plural = Str::plural($this->originalName); //Model Plural key $model_plural_key = strtolower(Str::plural($this->model)); //Path to that language files $path = resource_path('lang'.DIRECTORY_SEPARATOR.'en'); //config folder path $config_path = config_path('module.php'); //Creating directory if it isn't $this->createDirectory($path); //Labels file $labels = [ 'create' => "Create $model_singular", 'edit' => "Edit $model_singular", 'management' => "$model_singular Management", 'title' => "$model_plural", 'table' => [ 'id' => 'Id', 'createdat' => 'Created At', ], ]; //Pushing values to labels add_key_value_in_file($path.'/labels.php', [$model_plural_key => $labels], 'backend'); //Menus file $menus = [ 'all' => "All $model_plural", 'create' => "Create $model_singular", 'edit' => "Edit $model_singular", 'management' => "$model_singular Management", 'main' => "$model_plural", ]; //Pushing to menus file add_key_value_in_file($path.'/menus.php', [$model_plural_key => $menus], 'backend'); //Exceptions file $exceptions = [ 'already_exists' => "That $model_singular already exists. Please choose a different name.", 'create_error' => "There was a problem creating this $model_singular. Please try again.", 'delete_error' => "There was a problem deleting this $model_singular. Please try again.", 'not_found' => "That $model_singular does not exist.", 'update_error' => "There was a problem updating this $model_singular. Please try again.", ]; //Alerts File $alerts = [ 'created' => "The $model_singular was successfully created.", 'deleted' => "The $model_singular was successfully deleted.", 'updated' => "The $model_singular was successfully updated.", ]; //Pushing to menus file add_key_value_in_file($path.'/alerts.php', [$model_plural_key => $alerts], 'backend'); //Pushing to exceptions file add_key_value_in_file($path.'/exceptions.php', [$model_plural_key => $exceptions], 'backend'); //config file "module.php" $config = [ $model_plural_key => [ 'table' => $this->table, ], ]; //Pushing to config file add_key_value_in_file($config_path, $config); }
php
{ "resource": "" }
q257042
Generator.createViewFiles
test
public function createViewFiles() { //Getiing model $model = $this->model; //lowercase version of model $model_lower = strtolower($model); //lowercase and plural version of model $model_lower_plural = Str::plural($model_lower); //View folder name $view_folder_name = $model_lower_plural; //View path $path = escapeSlashes(strtolower(Str::plural($this->view_path))); //Header buttons folder $header_button_path = $path.DIRECTORY_SEPARATOR.'partials'; //This would create both the directory name as well as partials inside of that directory $this->createDirectory(base_path($header_button_path)); //Header button full path $header_button_file_path = $header_button_path.DIRECTORY_SEPARATOR."$model_lower_plural-header-buttons.blade"; //Getting stub file content $header_button_contents = $this->files->get($this->getStubPath().'header-buttons.stub'); if (!$this->create) { $header_button_contents = $this->delete_all_between('@create', '@endCreate', $header_button_contents); } else { $header_button_contents = $this->delete_all_between('@create', '@create', $header_button_contents); $header_button_contents = $this->delete_all_between('@endCreate', '@endCreate', $header_button_contents); } //Generate Header buttons file $this->generateFile(false, ['dummy_small_plural_model' => $model_lower_plural, 'dummy_small_model' => $model_lower], $header_button_file_path, $header_button_contents); //Index blade $index_path = $path.DIRECTORY_SEPARATOR.'index.blade'; //Generate the Index blade file $this->generateFile('index_view', ['dummy_small_plural_model' => $model_lower_plural], $index_path); //Create Blade if ($this->create) { //Create Blade $create_path = $path.DIRECTORY_SEPARATOR.'create.blade'; //Generate Create Blade $this->generateFile('create_view', ['dummy_small_plural_model' => $model_lower_plural, 'dummy_small_model' => $model_lower], $create_path); } //Edit Blade if ($this->edit) { //Edit Blade $edit_path = $path.DIRECTORY_SEPARATOR.'edit.blade'; //Generate Edit Blade $this->generateFile('edit_view', ['dummy_small_plural_model' => $model_lower_plural, 'dummy_small_model' => $model_lower], $edit_path); } //Form Blade if ($this->create || $this->edit) { //Form Blade $form_path = $path.DIRECTORY_SEPARATOR.'form.blade'; //Generate Form Blade $this->generateFile('form_view', [], $form_path); } //BreadCrumbs Folder Path $breadcrumbs_path = escapeSlashes('app\\Http\\Breadcrumbs\\Backend'); //Breadcrumb File path $breadcrumb_file_path = $breadcrumbs_path.DIRECTORY_SEPARATOR.$this->model; //Generate BreadCrumb File $this->generateFile('Breadcrumbs', ['dummy_small_plural_model' => $model_lower_plural], $breadcrumb_file_path); //Backend File of Breadcrumb $breadcrumb_backend_file = $breadcrumbs_path.DIRECTORY_SEPARATOR.'Backend.php'; //file_contents of Backend.php $file_contents = file_get_contents(base_path($breadcrumb_backend_file)); //If this is already not there, then only append if (!strpos($file_contents, "require __DIR__.'/$this->model.php';")) { //Appending into BreadCrumb backend file file_put_contents(base_path($breadcrumb_backend_file), "\nrequire __DIR__.'/$this->model.php';", FILE_APPEND); } }
php
{ "resource": "" }
q257043
Generator.createMigration
test
public function createMigration() { $table = $this->table; if (Schema::hasTable($table)) { return 'Table Already Exists!'; } else { //Calling Artisan command to create table Artisan::call('make:migration', [ 'name' => 'create_'.$table.'_table', '--create' => $table, ]); return Artisan::output(); } }
php
{ "resource": "" }
q257044
Generator.createEvents
test
public function createEvents() { if (!empty($this->events)) { $base_path = $this->event_namespace; foreach ($this->events as $event) { $path = escapeSlashes($base_path.DIRECTORY_SEPARATOR.$event); $model = str_replace(DIRECTORY_SEPARATOR, '\\', $path); Artisan::call('make:event', [ 'name' => $model, ]); Artisan::call('make:listener', [ 'name' => $model.'Listener', '--event' => $model, ]); } } }
php
{ "resource": "" }
q257045
Generator.generateFile
test
public function generateFile($stub_name, $replacements, $file, $contents = null) { if ($stub_name) { //Getting the Stub Files Content $file_contents = $this->files->get($this->getStubPath().$stub_name.'.stub'); } else { //Getting the Stub Files Content $file_contents = $contents; } //Replacing the stub $file_contents = str_replace( array_keys($replacements), array_values($replacements), $file_contents ); $this->files->put(base_path(escapeSlashes($file)).'.php', $file_contents); }
php
{ "resource": "" }
q257046
Generator.getStubPath
test
public function getStubPath() { $path = resource_path('views'.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'generator'.DIRECTORY_SEPARATOR.'Stubs'.DIRECTORY_SEPARATOR); $package_stubs_path = base_path('vendor'.DIRECTORY_SEPARATOR.'bvipul'.DIRECTORY_SEPARATOR.'generator'.DIRECTORY_SEPARATOR.'src'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.'Stubs'.DIRECTORY_SEPARATOR); if($this->files->exists($path)) return $path; else return $package_stubs_path; }
php
{ "resource": "" }
q257047
ModuleController.checkNamespace
test
public function checkNamespace(Request $request) { if (isset($request->path)) { $path = $this->parseModel($request->path); $path = base_path(trim(str_replace('\\', '/', $request->path)), '\\'); $path = str_replace('App', 'app', $path); if (file_exists($path.'.php')) { return response()->json((object) [ 'type' => 'error', 'message' => 'File exists Already', ]); } else { return response()->json((object) [ 'type' => 'success', 'message' => 'File can be generated at this location', ]); } } else { return response()->json((object) [ 'type' => 'error', 'message' => 'Please provide some value', ]); } }
php
{ "resource": "" }
q257048
ModuleController.checkTable
test
public function checkTable(Request $request) { if ($request->table) { if (Schema::hasTable($request->table)) { return response()->json((object) [ 'type' => 'error', 'message' => 'Table exists Already', ]); } else { return response()->json((object) [ 'type' => 'success', 'message' => 'Table Name Available', ]); } } else { return response()->json((object) [ 'type' => 'error', 'message' => 'Please provide some value', ]); } }
php
{ "resource": "" }
q257049
Multi.onOneRandomServer
test
public function onOneRandomServer() { $keys = array_keys($this->getServerConfig()); do { $randServerRank = array_rand($keys); if ($redis = $this->getRedisFromServerConfig($keys[$randServerRank])) { $this->selectedRedis = array($keys[$randServerRank] => $redis); } else { unset($keys[$randServerRank]); } } while (!empty($keys) && empty($this->selectedRedis)); if (empty($this->selectedRedis)) { throw new Exception("Can't connect to a random redis server"); } $this->multiRedis = false; return $this; }
php
{ "resource": "" }
q257050
Multi.onAllServer
test
public function onAllServer($strict = true) { foreach ($this->getServerConfig() as $idServer => $config) { if ($redis = $this->getRedisFromServerConfig($idServer)) { $this->selectedRedis[$idServer] = $redis; } else { if ($strict) { throw new Exception('cant connect to redis '.$idServer); } } } $this->multiRedis = true; return $this; }
php
{ "resource": "" }
q257051
Multi.onOneServer
test
public function onOneServer($idServer, $strict = true) { $redisList = $this->getServerConfig(); // The server must exist.. if (array_key_exists($idServer, $redisList)) { // and must be available if ($redis = $this->getRedisFromServerConfig($idServer)) { $this->selectedRedis[$idServer] = $redis; } else { if ($strict) { throw new Exception('cant connect to redis ' . $idServer); } } } else { throw new Exception('unknown redis '.$idServer); } $this->multiRedis = false; return $this; }
php
{ "resource": "" }
q257052
Multi.onOneKeyServer
test
public function onOneKeyServer($key) { $this->selectedRedis[] = $this->getRedis($key); $this->multiRedis = false; return $this; }
php
{ "resource": "" }
q257053
Multi.callRedisCommand
test
protected function callRedisCommand(PredisProxy $redis, $name, $arguments) { $start = microtime(true); try { $return = call_user_func_array(array($redis, $name), $arguments); $this->notifyEvent($name, $arguments, microtime(true) - $start); } catch (Predis\PredisException $e) { throw new Exception("Error calling the method ".$name." : ".$e->getMessage()); } return $return; }
php
{ "resource": "" }
q257054
Manager.setCurrentDb
test
public function setCurrentDb($v) { if (!is_int($v)) { throw new Exception("please describe the db as an integer ^^"); } if ($v == Cache::CACHE) { throw new Exception("cant use ".Cache::CACHE." in class ".__CLASS__); } $this->currentDb = $v; return $this; }
php
{ "resource": "" }
q257055
Cache.del
test
public function del($keys) { if (!is_array($keys)) { $keys = array($keys); } $funcs = array(); // séparation en serveur foreach ($keys as $key) { $keyP = $this->getPatternKey().$key; $funcs[$key] = function ($redis) use ($keyP) { $start = microtime(true); $count = $redis->del($keyP); if ((is_int($count)) and ($count > 0)) { $this->notifyEvent('del', array($keyP), microtime(true) - $start); } return $count; }; } if (true === $this->multi) { //throw new Exception("not implemented yet"); foreach ($funcs as $k => $func) { $this->addToExecList($k, $func); } return $this; } else { $ret = 0; foreach ($funcs as $k => $func) { $ret += $func($this->getRedis($k)); // execution } return $ret; } }
php
{ "resource": "" }
q257056
Cache.set
test
public function set($key, $value, $ttl = null) { if ($this->getCompress()) { $value = self::compress($value); } $keyP = $this->getPatternKey().$key; if (is_null($ttl)) { $func = function ($redis) use ($keyP, $value) { $start = microtime(true); $redis->set($keyP, $value); $this->notifyEvent('set', array($keyP, $value), microtime(true) - $start); return $redis; }; } else { $func = function ($redis) use ($keyP, $value, $ttl) { $start = microtime(true); $redis->setex($keyP, $ttl, $value); $this->notifyEvent('setex', array($keyP, $ttl, $value), microtime(true) - $start); return $redis; }; } if (true === $this->multi) { $this->addToExecList($key, $func); } else { $func($this->getRedis($key)); // set "normal" } return $this; }
php
{ "resource": "" }
q257057
Cache.exists
test
public function exists($key) { $start = microtime(true); $ret = $this->getRedis($key)->exists($this->getPatternKey().$key); $this->notifyEvent('exists', array($this->getPatternKey().$key), microtime(true) - $start); return (boolean) $ret; }
php
{ "resource": "" }
q257058
Cache.type
test
public function type($key) { $start = microtime(true); $ret = (string)$this->getRedis($key)->type($this->getPatternKey().$key); $this->notifyEvent('type', array($this->getPatternKey().$key), microtime(true) - $start); return $ret; }
php
{ "resource": "" }
q257059
Cache.expire
test
public function expire($key, $ttl) { if ($ttl <= 0) { throw new Exception('ttl arg cant be negative'); } $keyP = $this->getPatternKey().$key; $func = function ($redis) use ($keyP, $ttl) { try { $start = microtime(true); $ret = $redis->expire($keyP, $ttl); $this->notifyEvent('expire', array($keyP, $ttl), microtime(true) - $start); return $ret; } catch (Predis\ServerException $e) { return null; } }; // gestion du multi if (true === $this->multi) { $this->addToExecList($key, $func); return $this; } else { $ret = $func($this->getRedis($key)); return $ret; } }
php
{ "resource": "" }
q257060
Cache.flush
test
public function flush() { $pattern = $this->getPatternKey(); $arrReturn = $this->runOnAllRedisServer( function ($redis) use ($pattern) { $wasDeleted = 0; $allKeys = $redis->keys($pattern.'*'); // all keys started with the namespace if (count($allKeys)) { $wasDeleted = $redis->del($allKeys); } return array($wasDeleted); } ); return array_sum($arrReturn); }
php
{ "resource": "" }
q257061
Cache.exec
test
public function exec() { if (true === $this->multi) { $ret = array(); $this->multi = false; // exec foreach ($this->execList as $todos) { $redis = $todos[0]['redis']; // ^^ not so secure ? $this->notifyEvent('multi', array()); $redis->multi(); foreach ($todos as $todo) { if ($todo['function'] instanceof \Closure) { $ret[] = $todo['function']($redis); } else { throw new Exception("Ce n'est pas une Closure !"); } } $this->notifyEvent('exec', array()); $redis->exec(); } $this->execList = array(); // purge the execList return $ret; } else { throw new Exception("you have to call multi before exec"); } }
php
{ "resource": "" }
q257062
Cache.dbSize
test
public function dbSize($idServer = null) { if (is_null($idServer)) { $servers = $this->getServerConfig(); $dbsize = array(); foreach (array_keys($servers) as $idServer) { $redis = $this->getRedisFromServerConfig($idServer); $dbsize[$idServer] = $redis->dbsize(); } } else { $redis = $this->getRedisFromServerConfig($idServer); $dbsize = $redis->dbsize(); } return $dbsize; }
php
{ "resource": "" }
q257063
Cache.addToExecList
test
protected function addToExecList($key, \Closure $func) { $redis = $this->getRedis($key); $this->execList[md5(serialize($redis))][] = array( 'key' => $key, 'function' => $func, 'redis' => $redis ); }
php
{ "resource": "" }
q257064
ConsoleListener.dispatch
test
protected function dispatch($eventName, BaseConsoleEvent $e) { if (!is_null($this->eventDispatcher)) { $class = str_replace( 'Symfony\Component\Console\Event', 'M6Web\Bundle\StatsdBundle\Event', get_class($e) ); $finaleEvent = $class::createFromConsoleEvent( $e, $this->startTime, !is_null($this->startTime) ? microtime(true) - $this->startTime : null ); return $this->eventDispatcher->dispatch($eventName, $finaleEvent); } else { return false; } }
php
{ "resource": "" }
q257065
Client.addTiming
test
private function addTiming($event, $timingMethod, $node, $tags = []) { $timing = $this->getEventValue($event, $timingMethod); if ($timing > 0) { $this->timing($node, $timing, 1, $tags); } }
php
{ "resource": "" }
q257066
Client.replaceConfigPlaceholder
test
private function replaceConfigPlaceholder($event, $eventName, $string) { // `event->getName()` is deprecated, we have to replace <name> directly with $eventName $string = str_replace('<name>', $eventName, $string); if ((preg_match_all('/<([^>]*)>/', $string, $matches) > 0) and ($this->propertyAccessor !== null)) { $tokens = $matches[1]; foreach ($tokens as $token) { $value = $this->propertyAccessor->getValue($event, $token); $string = str_replace('<'.$token.'>', $value, $string); } } return $string; }
php
{ "resource": "" }
q257067
Client.mergeTags
test
private function mergeTags($event, $config) { $configTags = isset($config['tags']) ? $config['tags'] : []; if ($event instanceof MonitorableEventInterface) { return array_merge($configTags, $event->getTags()); } return $configTags; }
php
{ "resource": "" }
q257068
Listener.dispatchMemory
test
private function dispatchMemory() { $memory = memory_get_peak_usage(true); $memory = ($memory > 1024 ? intval($memory / 1024) : 0); $this->eventDispatcher->dispatch( 'statsd.memory_usage', new StatsdEvent($memory) ); }
php
{ "resource": "" }
q257069
Listener.dispatchRequestTime
test
private function dispatchRequestTime(PostResponseEvent $event) { $request = $event->getRequest(); $startTime = $request->server->get('REQUEST_TIME_FLOAT', $request->server->get('REQUEST_TIME')); $time = microtime(true) - $startTime; $time = round($time * 1000); $this->eventDispatcher->dispatch( 'statsd.time', new StatsdEvent($time) ); }
php
{ "resource": "" }
q257070
ConsoleEvent.createFromConsoleEvent
test
public static function createFromConsoleEvent(BaseConsoleEvent $e, $startTime = null, $executionTime = null) { if (static::support($e)) { return new static($e, $startTime, $executionTime); } else { throw \InvalidArgumentException('Invalid event type.'); } }
php
{ "resource": "" }
q257071
Parser.srid
test
protected function srid() { $this->match(Lexer::T_SRID); $this->match(Lexer::T_EQUALS); $this->match(Lexer::T_INTEGER); $srid = $this->lexer->value(); $this->match(Lexer::T_SEMICOLON); return $srid; }
php
{ "resource": "" }
q257072
Parser.geometry
test
protected function geometry() { $type = $this->type(); $this->type = $type; if ($this->lexer->isNextTokenAny(array(Lexer::T_Z, Lexer::T_M, Lexer::T_ZM))) { $this->match($this->lexer->lookahead['type']); $this->dimension = $this->lexer->value(); } $this->match(Lexer::T_OPEN_PARENTHESIS); $value = $this->$type(); $this->match(Lexer::T_CLOSE_PARENTHESIS); return array( 'type' => $type, 'value' => $value ); }
php
{ "resource": "" }
q257073
Parser.point
test
protected function point() { if (null !== $this->dimension) { return $this->coordinates(2 + strlen($this->dimension)); } $values = $this->coordinates(2); for ($i = 3; $i <= 4 && $this->lexer->isNextTokenAny(array(Lexer::T_FLOAT, Lexer::T_INTEGER)); $i++) { $values[] = $this->coordinate(); } switch (count($values)) { case 2: $this->dimension = ''; break; case 3: $this->dimension = 'Z'; break; case 4: $this->dimension = 'ZM'; break; } return $values; }
php
{ "resource": "" }
q257074
Parser.coordinate
test
protected function coordinate() { $this->match(($this->lexer->isNextToken(Lexer::T_FLOAT) ? Lexer::T_FLOAT : Lexer::T_INTEGER)); return $this->lexer->value(); }
php
{ "resource": "" }
q257075
Parser.pointList
test
protected function pointList() { $points = array($this->point()); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { $this->match(Lexer::T_COMMA); $points[] = $this->point(); } return $points; }
php
{ "resource": "" }
q257076
Parser.pointLists
test
protected function pointLists() { $this->match(Lexer::T_OPEN_PARENTHESIS); $pointLists = array($this->pointList()); $this->match(Lexer::T_CLOSE_PARENTHESIS); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { $this->match(Lexer::T_COMMA); $this->match(Lexer::T_OPEN_PARENTHESIS); $pointLists[] = $this->pointList(); $this->match(Lexer::T_CLOSE_PARENTHESIS); } return $pointLists; }
php
{ "resource": "" }
q257077
Parser.multiPolygon
test
protected function multiPolygon() { $this->match(Lexer::T_OPEN_PARENTHESIS); $polygons = array($this->polygon()); $this->match(Lexer::T_CLOSE_PARENTHESIS); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { $this->match(Lexer::T_COMMA); $this->match(Lexer::T_OPEN_PARENTHESIS); $polygons[] = $this->polygon(); $this->match(Lexer::T_CLOSE_PARENTHESIS); } return $polygons; }
php
{ "resource": "" }
q257078
Parser.geometryCollection
test
protected function geometryCollection() { $collection = array($this->geometry()); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { $this->match(Lexer::T_COMMA); $collection[] = $this->geometry(); } return $collection; }
php
{ "resource": "" }
q257079
Parser.match
test
protected function match($token) { $lookaheadType = $this->lexer->lookahead['type']; if ($lookaheadType !== $token && ($token !== Lexer::T_TYPE || $lookaheadType <= Lexer::T_TYPE)) { throw $this->syntaxError($this->lexer->getLiteral($token)); } $this->lexer->moveNext(); }
php
{ "resource": "" }
q257080
Parser.syntaxError
test
private function syntaxError($expected) { $expected = sprintf('Expected %s, got', $expected); $token = $this->lexer->lookahead; $found = null === $this->lexer->lookahead ? 'end of string.' : sprintf('"%s"', $token['value']); $message = sprintf( '[Syntax Error] line 0, col %d: Error: %s %s in value "%s"', isset($token['position']) ? $token['position'] : '-1', $expected, $found, $this->input ); return new UnexpectedValueException($message); }
php
{ "resource": "" }
q257081
Request.createResponseParts
test
protected function createResponseParts($responseParts) { if ($responseParts === null) { return array(); } $responses = array(); foreach ($responseParts as $responsePart) { $responses[] = new Response($responsePart); } return $responses; }
php
{ "resource": "" }
q257082
Request.getTime
test
public function getTime() { if (isset($this->data['time'])) { $requestTime = new \DateTime(); //TODO: fix the microseconds to miliseconds $requestTime->createFromFormat("Y-m-dTH:i:s.uZ", $this->data["time"]); return $requestTime; } return null; }
php
{ "resource": "" }
q257083
BrowserBase.createApiClient
test
protected function createApiClient() { // Provide a BC switch between guzzle 5 and guzzle 6. if (class_exists('GuzzleHttp\Psr7\Response')) { $this->apiClient = new Client(array("base_uri" => $this->getPhantomJSHost())); } else { $this->apiClient = new Client(array("base_url" => $this->getPhantomJSHost())); } }
php
{ "resource": "" }
q257084
BrowserBase.command
test
public function command() { try { $args = func_get_args(); $commandName = $args[0]; array_shift($args); $messageToSend = json_encode(array('name' => $commandName, 'args' => $args)); /** @var $commandResponse \GuzzleHttp\Psr7\Response|\GuzzleHttp\Message\Response */ $commandResponse = $this->getApiClient()->post("/api", array("body" => $messageToSend)); $jsonResponse = json_decode($commandResponse->getBody(), TRUE); } catch (ServerException $e) { $jsonResponse = json_decode($e->getResponse()->getBody()->getContents(), true); } catch (ConnectException $e) { throw new DeadClient($e->getMessage(), $e->getCode(), $e); } catch (\Exception $e) { throw $e; } if (isset($jsonResponse['error'])) { throw $this->getErrorClass($jsonResponse); } return $jsonResponse['response']; }
php
{ "resource": "" }
q257085
Response.getRedirectUrl
test
public function getRedirectUrl() { if (isset($this->data['redirectUrl']) && !empty($this->data['redirectUrl'])) { return $this->data['redirectUrl']; } return null; }
php
{ "resource": "" }
q257086
BrowserRenderTrait.checkRenderOptions
test
protected function checkRenderOptions($options) { //Default is full and no selection if (count($options) === 0) { $options["full"] = true; $options["selector"] = null; } if (isset($options["full"]) && isset($options["selector"])) { if ($options["full"]) { //Whatever it is, full is more powerful than selection $options["selector"] = null; } } else { if (!isset($options["full"]) && isset($options["selector"])) { $options["full"] = false; } } return $options; }
php
{ "resource": "" }
q257087
BrowserRenderTrait.render
test
public function render($path, $options = array()) { $fixedOptions = $this->checkRenderOptions($options); return $this->command('render', $path, $fixedOptions["full"], $fixedOptions["selector"]); }
php
{ "resource": "" }
q257088
BrowserRenderTrait.renderBase64
test
public function renderBase64($imageFormat, $options = array()) { $fixedOptions = $this->checkRenderOptions($options); return $this->command('render_base64', $imageFormat, $fixedOptions["full"], $fixedOptions["selector"]); }
php
{ "resource": "" }
q257089
BrowserPageElementTrait.find
test
public function find($method, $selector) { $result = $this->command('find', $method, $selector); $found["page_id"] = $result["page_id"]; foreach ($result["ids"] as $id) { $found["ids"][] = $id; } return $found; }
php
{ "resource": "" }
q257090
BrowserPageElementTrait.findWithin
test
public function findWithin($pageId, $elementId, $method, $selector) { return $this->command('find_within', $pageId, $elementId, $method, $selector); }
php
{ "resource": "" }
q257091
BrowserPageElementTrait.setAttribute
test
public function setAttribute($pageId, $elementId, $name, $value) { return $this->command('set_attribute', $pageId, $elementId, $name, $value); }
php
{ "resource": "" }
q257092
BrowserPageElementTrait.keyEvent
test
public function keyEvent($pageId, $elementId, $keyEvent, $key, $modifier) { return $this->command("key_event", $pageId, $elementId, $keyEvent, $key, $modifier); }
php
{ "resource": "" }
q257093
BrowserPageElementTrait.selectOption
test
public function selectOption($pageId, $elementId, $value, $multiple = false) { return $this->command("select_option", $pageId, $elementId, $value, $multiple); }
php
{ "resource": "" }
q257094
BrowserConfigurationTrait.debug
test
public function debug($enable = false) { $this->debug = $enable; return $this->command('set_debug', $this->debug); }
php
{ "resource": "" }
q257095
BrowserConfigurationTrait.setProxy
test
public function setProxy($proxy) { $args = array('set_proxy'); if ($proxy !== false) { if (preg_match('~^(http|socks5)://(?:([^:@/]*?):([^:@/]*?)@)?([^:@/]+):(\d+)$~', $proxy, $components)) { array_push($args, $components[4], intval($components[5], 10), $components[1]); if (strlen($components[2]) || strlen($components[3])) { array_push($args, urldecode($components[2]), urldecode($components[3])); } } else { throw new \UnexpectedValueException('Invalid proxy url ' . $proxy); } } return call_user_func_array(array($this, 'command'), $args); }
php
{ "resource": "" }
q257096
BrowserNetworkTrait.networkTraffic
test
public function networkTraffic() { $networkTraffic = $this->command('network_traffic'); $requestTraffic = array(); if (count($networkTraffic) === 0) { return null; } foreach ($networkTraffic as $traffic) { $requestTraffic[] = new Request($traffic["request"], $traffic["responseParts"]); } return $requestTraffic; }
php
{ "resource": "" }
q257097
BrowserCookieTrait.cookies
test
public function cookies() { $cookies = $this->command('cookies'); $objCookies = array(); foreach ($cookies as $cookie) { $objCookies[$cookie["name"]] = new Cookie($cookie); } return $objCookies; }
php
{ "resource": "" }
q257098
BrowserCookieTrait.setCookie
test
public function setCookie($cookie) { //TODO: add error control when the cookie array is not valid if (isset($cookie["expires"])) { $cookie["expires"] = intval($cookie["expires"]) * 1000; } $cookie['value'] = urlencode($cookie['value']); return $this->command('set_cookie', $cookie); }
php
{ "resource": "" }
q257099
JavascriptError.javascriptErrors
test
public function javascriptErrors() { $jsErrors = array(); $errors = $this->response["error"]["args"][0]; foreach ($errors as $error) { $jsErrors[] = new JSErrorItem($error["message"], $error["stack"]); } return $jsErrors; }
php
{ "resource": "" }