_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q255600
SplitItem.setDefaultSelectedItem
test
private function setDefaultSelectedItem() : void { foreach ($this->items as $index => $item) { if ($item->canSelect()) { $this->canBeSelected = true; $this->selectedItemIndex = $index; return; } } $this->canBeSelected = false; $this->selectedItemIndex = null; }
php
{ "resource": "" }
q255601
SplitItem.canSelectIndex
test
public function canSelectIndex(int $index) : bool { return isset($this->items[$index]) && $this->items[$index]->canSelect(); }
php
{ "resource": "" }
q255602
SplitItem.setSelectedItemIndex
test
public function setSelectedItemIndex(int $index) : void { if (!isset($this->items[$index])) { throw new \InvalidArgumentException(sprintf('Index: "%s" does not exist', $index)); } $this->selectedItemIndex = $index; }
php
{ "resource": "" }
q255603
SplitItem.getSelectedItem
test
public function getSelectedItem() : MenuItemInterface { if (null === $this->selectedItemIndex) { throw new \RuntimeException('No item is selected'); } return $this->items[$this->selectedItemIndex]; }
php
{ "resource": "" }
q255604
StringUtil.wordwrap
test
public static function wordwrap(string $string, int $width, string $break = "\n") : string { return implode( $break, array_map(function (string $line) use ($width, $break) { $line = rtrim($line); if (mb_strlen($line) <= $width) { return $line; } $words = explode(' ', $line); $line = ''; $actual = ''; foreach ($words as $word) { if (mb_strlen($actual . $word) <= $width) { $actual .= $word . ' '; } else { if ($actual !== '') { $line .= rtrim($actual) . $break; } $actual = $word . ' '; } } return $line . trim($actual); }, explode("\n", $string)) ); }
php
{ "resource": "" }
q255605
MenuStyle.generateColoursSetCode
test
private function generateColoursSetCode() : void { if (!ctype_digit($this->fg)) { $fgCode = self::$availableForegroundColors[$this->fg]; } else { $fgCode = sprintf("38;5;%s", $this->fg); } if (!ctype_digit($this->bg)) { $bgCode = self::$availableBackgroundColors[$this->bg]; } else { $bgCode = sprintf("48;5;%s", $this->bg); } $this->coloursSetCode = sprintf("\033[%s;%sm", $fgCode, $bgCode); }
php
{ "resource": "" }
q255606
MenuStyle.calculateContentWidth
test
protected function calculateContentWidth() : void { $this->contentWidth = $this->width - ($this->paddingLeftRight * 2) - ($this->borderRightWidth + $this->borderLeftWidth); if ($this->contentWidth < 0) { $this->contentWidth = 0; } }
php
{ "resource": "" }
q255607
MenuStyle.getRightHandPadding
test
public function getRightHandPadding(int $contentLength) : int { $rightPadding = $this->getContentWidth() - $contentLength + $this->getPaddingLeftRight(); if ($rightPadding < 0) { $rightPadding = 0; } return $rightPadding; }
php
{ "resource": "" }
q255608
MenuStyle.setBorder
test
public function setBorder( int $topWidth, $rightWidth = null, $bottomWidth = null, $leftWidth = null, string $colour = null ) : self { if (!is_int($rightWidth)) { $colour = $rightWidth; $rightWidth = $bottomWidth = $leftWidth = $topWidth; } elseif (!is_int($bottomWidth)) { $colour = $bottomWidth; $bottomWidth = $topWidth; $leftWidth = $rightWidth; } elseif (!is_int($leftWidth)) { $colour = $leftWidth; $leftWidth = $rightWidth; } $this->borderTopWidth = $topWidth; $this->borderRightWidth = $rightWidth; $this->borderBottomWidth = $bottomWidth; $this->borderLeftWidth = $leftWidth; if (is_string($colour)) { $this->setBorderColour($colour); } elseif ($colour !== null) { throw new \InvalidArgumentException('Invalid colour'); } $this->calculateContentWidth(); $this->generateBorderRows(); $this->generatePaddingTopBottomRows(); return $this; }
php
{ "resource": "" }
q255609
Flash.display
test
public function display() : void { $this->assertMenuOpen(); $this->terminal->moveCursorToRow($this->y); $this->emptyRow(); $this->write(sprintf( "%s%s%s%s%s\n", $this->style->getColoursSetCode(), str_repeat(' ', $this->style->getPaddingLeftRight()), $this->text, str_repeat(' ', $this->style->getPaddingLeftRight()), $this->style->getColoursResetCode() )); $this->emptyRow(); $this->terminal->moveCursorToTop(); $reader = new NonCanonicalReader($this->terminal); $reader->readCharacter(); $this->parentMenu->redraw(); }
php
{ "resource": "" }
q255610
Dialogue.calculateCoordinates
test
protected function calculateCoordinates() : void { //y $textLines = count(explode("\n", $this->text)) + 2; $this->y = (int) (ceil($this->parentMenu->getCurrentFrame()->count() / 2) - ceil($textLines / 2) + 1); //x $parentStyle = $this->parentMenu->getStyle(); $dialogueHalfLength = (int) ((mb_strlen($this->text) + ($this->style->getPaddingLeftRight() * 2)) / 2); $widthHalfLength = (int) ceil($parentStyle->getWidth() / 2 + $parentStyle->getMargin()); $this->x = $widthHalfLength - $dialogueHalfLength; }
php
{ "resource": "" }
q255611
Dialogue.emptyRow
test
protected function emptyRow() : void { $this->write( sprintf( "%s%s%s%s%s\n", $this->style->getColoursSetCode(), str_repeat(' ', $this->style->getPaddingLeftRight()), str_repeat(' ', mb_strlen($this->text)), str_repeat(' ', $this->style->getPaddingLeftRight()), $this->style->getColoursResetCode() ) ); }
php
{ "resource": "" }
q255612
Dialogue.write
test
protected function write(string $text, int $column = null) : void { $this->terminal->moveCursorToColumn($column ?: $this->x); $this->terminal->write($text); }
php
{ "resource": "" }
q255613
AsciiArtItem.setText
test
public function setText(string $text) : void { $this->text = implode("\n", array_map(function (string $line) { return rtrim($line, ' '); }, explode("\n", $text))); $this->calculateArtLength(); }
php
{ "resource": "" }
q255614
AsciiArtItem.calculateArtLength
test
private function calculateArtLength() : void { $this->artLength = (int) max(array_map('mb_strlen', explode("\n", $this->text))); }
php
{ "resource": "" }
q255615
Confirm.display
test
public function display(string $confirmText = 'OK') : void { $this->assertMenuOpen(); $this->terminal->moveCursorToRow($this->y); $promptWidth = mb_strlen($this->text) + 4; $this->emptyRow(); $this->write(sprintf( "%s%s%s%s%s\n", $this->style->getColoursSetCode(), str_repeat(' ', $this->style->getPaddingLeftRight()), $this->text, str_repeat(' ', $this->style->getPaddingLeftRight()), $this->style->getColoursResetCode() )); $this->emptyRow(); $confirmText = sprintf(' < %s > ', $confirmText); $leftFill = (int) (($promptWidth / 2) - (mb_strlen($confirmText) / 2)); $this->write(sprintf( "%s%s%s%s%s%s%s\n", $this->style->getColoursSetCode(), str_repeat(' ', $leftFill), $this->style->getInvertedColoursSetCode(), $confirmText, $this->style->getInvertedColoursUnsetCode(), str_repeat(' ', (int) ceil($promptWidth - $leftFill - mb_strlen($confirmText))), $this->style->getColoursResetCode() )); $this->write(sprintf( "%s%s%s%s%s\n", $this->style->getColoursSetCode(), str_repeat(' ', $this->style->getPaddingLeftRight()), str_repeat(' ', mb_strlen($this->text)), str_repeat(' ', $this->style->getPaddingLeftRight()), $this->style->getColoursResetCode() )); $this->terminal->moveCursorToTop(); $reader = new NonCanonicalReader($this->terminal); while ($char = $reader->readCharacter()) { if ($char->isControl() && $char->getControl() === InputCharacter::ENTER) { $this->parentMenu->redraw(); return; } } }
php
{ "resource": "" }
q255616
Manager.connection
test
public function connection(string $name = null): Client { $name = $name ?: $this->getDefaultConnection(); if (!isset($this->connections[$name])) { $client = $this->makeConnection($name); $this->connections[$name] = $client; } return $this->connections[$name]; }
php
{ "resource": "" }
q255617
Manager.makeConnection
test
protected function makeConnection(string $name): Client { $config = $this->getConfig($name); return $this->factory->make($config); }
php
{ "resource": "" }
q255618
Manager.getConfig
test
protected function getConfig(string $name) { $connections = $this->app['config']['elasticsearch.connections']; if (null === $config = array_get($connections, $name)) { throw new \InvalidArgumentException("Elasticsearch connection [$name] not configured."); } return $config; }
php
{ "resource": "" }
q255619
DeflateCompressor.Compress
test
public function Compress(&$curl_headers, &$requestBody) { if (!function_exists('gzencode')) { return; } $requestBody = gzencode($requestBody); $curl_headers['content-encoding']='deflate'; $curl_headers['content-length']=strlen($requestBody); }
php
{ "resource": "" }
q255620
Zend_Console_Getopt.__isset
test
public function __isset($key) { $this->parse(); if (isset($this->_ruleMap[$key])) { $key = $this->_ruleMap[$key]; return isset($this->_options[$key]); } return false; }
php
{ "resource": "" }
q255621
Zend_Console_Getopt.addArguments
test
public function addArguments($argv) { if (!is_array($argv)) { require_once 'Zend/Console/Getopt/Exception.php'; throw new Zend_Console_Getopt_Exception( "Parameter #1 to addArguments should be an array"); } $this->_argv = array_merge($this->_argv, $argv); $this->_parsed = false; return $this; }
php
{ "resource": "" }
q255622
Zend_Console_Getopt.setArguments
test
public function setArguments($argv) { if (!is_array($argv)) { require_once 'Zend/Console/Getopt/Exception.php'; throw new Zend_Console_Getopt_Exception( "Parameter #1 to setArguments should be an array"); } $this->_argv = $argv; $this->_parsed = false; return $this; }
php
{ "resource": "" }
q255623
Zend_Console_Getopt.setOptions
test
public function setOptions($getoptConfig) { if (isset($getoptConfig)) { foreach ($getoptConfig as $key => $value) { $this->setOption($key, $value); } } return $this; }
php
{ "resource": "" }
q255624
Zend_Console_Getopt.addRules
test
public function addRules($rules) { $ruleMode = $this->_getoptConfig['ruleMode']; switch ($this->_getoptConfig['ruleMode']) { case self::MODE_ZEND: if (is_array($rules)) { $this->_addRulesModeZend($rules); break; } // intentional fallthrough case self::MODE_GNU: $this->_addRulesModeGnu($rules); break; default: /** * Call addRulesModeFoo() for ruleMode 'foo'. * The developer should subclass Getopt and * provide this method. */ $method = '_addRulesMode' . ucfirst($ruleMode); $this->$method($rules); } $this->_parsed = false; return $this; }
php
{ "resource": "" }
q255625
Zend_Console_Getopt.toString
test
public function toString() { $this->parse(); $s = array(); foreach ($this->_options as $flag => $value) { $s[] = $flag . '=' . ($value === true ? 'true' : $value); } return implode(' ', $s); }
php
{ "resource": "" }
q255626
Zend_Console_Getopt.toArray
test
public function toArray() { $this->parse(); $s = array(); foreach ($this->_options as $flag => $value) { $s[] = $flag; if ($value !== true) { $s[] = $value; } } return $s; }
php
{ "resource": "" }
q255627
Zend_Console_Getopt.toJson
test
public function toJson() { $this->parse(); $j = array(); foreach ($this->_options as $flag => $value) { $j['options'][] = array( 'option' => array( 'flag' => $flag, 'parameter' => $value ) ); } /** * @see Zend_Json */ require_once 'Zend/Json.php'; $json = Zend_Json::encode($j); return $json; }
php
{ "resource": "" }
q255628
Zend_Console_Getopt.toXml
test
public function toXml() { $this->parse(); $doc = new DomDocument('1.0', 'utf-8'); $optionsNode = $doc->createElement('options'); $doc->appendChild($optionsNode); foreach ($this->_options as $flag => $value) { $optionNode = $doc->createElement('option'); $optionNode->setAttribute('flag', utf8_encode($flag)); if ($value !== true) { $optionNode->setAttribute('parameter', utf8_encode($value)); } $optionsNode->appendChild($optionNode); } $xml = $doc->saveXML(); return $xml; }
php
{ "resource": "" }
q255629
Zend_Console_Getopt.getOption
test
public function getOption($flag) { $this->parse(); if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) { $flag = strtolower($flag); } if (isset($this->_ruleMap[$flag])) { $flag = $this->_ruleMap[$flag]; if (isset($this->_options[$flag])) { return $this->_options[$flag]; } } return null; }
php
{ "resource": "" }
q255630
Zend_Console_Getopt.getUsageMessage
test
public function getUsageMessage() { $usage = "Usage: {$this->_progname} [ options ]\n"; $maxLen = 20; $lines = array(); foreach ($this->_rules as $rule) { $flags = array(); if (is_array($rule['alias'])) { foreach ($rule['alias'] as $flag) { $flags[] = (strlen($flag) == 1 ? '-' : '--') . $flag; } } $linepart['name'] = implode('|', $flags); if (isset($rule['param']) && $rule['param'] != 'none') { $linepart['name'] .= ' '; switch ($rule['param']) { case 'optional': $linepart['name'] .= "[ <{$rule['paramType']}> ]"; break; case 'required': $linepart['name'] .= "<{$rule['paramType']}>"; break; } } if (strlen($linepart['name']) > $maxLen) { $maxLen = strlen($linepart['name']); } $linepart['help'] = ''; if (isset($rule['help'])) { $linepart['help'] .= $rule['help']; } $lines[] = $linepart; } foreach ($lines as $linepart) { $usage .= sprintf("%s %s\n", str_pad($linepart['name'], $maxLen), $linepart['help']); } return $usage; }
php
{ "resource": "" }
q255631
Zend_Console_Getopt.setAliases
test
public function setAliases($aliasMap) { foreach ($aliasMap as $flag => $alias) { if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) { $flag = strtolower($flag); $alias = strtolower($alias); } if (!isset($this->_ruleMap[$flag])) { continue; } $flag = $this->_ruleMap[$flag]; if (isset($this->_rules[$alias]) || isset($this->_ruleMap[$alias])) { $o = (strlen($alias) == 1 ? '-' : '--') . $alias; require_once 'Zend/Console/Getopt/Exception.php'; throw new Zend_Console_Getopt_Exception( "Option \"$o\" is being defined more than once."); } $this->_rules[$flag]['alias'][] = $alias; $this->_ruleMap[$alias] = $flag; } return $this; }
php
{ "resource": "" }
q255632
Zend_Console_Getopt.setHelp
test
public function setHelp($helpMap) { foreach ($helpMap as $flag => $help) { if (!isset($this->_ruleMap[$flag])) { continue; } $flag = $this->_ruleMap[$flag]; $this->_rules[$flag]['help'] = $help; } return $this; }
php
{ "resource": "" }
q255633
Zend_Console_Getopt.parse
test
public function parse() { if ($this->_parsed === true) { return; } $argv = $this->_argv; $this->_options = array(); $this->_remainingArgs = array(); while (count($argv) > 0) { if ($argv[0] == '--') { array_shift($argv); if ($this->_getoptConfig[self::CONFIG_DASHDASH]) { $this->_remainingArgs = array_merge($this->_remainingArgs, $argv); break; } } if (substr($argv[0], 0, 2) == '--') { $this->_parseLongOption($argv); } elseif (substr($argv[0], 0, 1) == '-' && ('-' != $argv[0] || count($argv) >1)) { $this->_parseShortOptionCluster($argv); } elseif ($this->_getoptConfig[self::CONFIG_PARSEALL]) { $this->_remainingArgs[] = array_shift($argv); } else { /* * We should put all other arguments in _remainingArgs and stop parsing * since CONFIG_PARSEALL is false. */ $this->_remainingArgs = array_merge($this->_remainingArgs, $argv); break; } } $this->_parsed = true; return $this; }
php
{ "resource": "" }
q255634
Zend_Console_Getopt._parseShortOptionCluster
test
protected function _parseShortOptionCluster(&$argv) { $flagCluster = ltrim(array_shift($argv), '-'); foreach (str_split($flagCluster) as $flag) { $this->_parseSingleOption($flag, $argv); } }
php
{ "resource": "" }
q255635
Zend_Console_Getopt._parseSingleOption
test
protected function _parseSingleOption($flag, &$argv) { if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) { $flag = strtolower($flag); } if (!isset($this->_ruleMap[$flag])) { require_once 'Zend/Console/Getopt/Exception.php'; throw new Zend_Console_Getopt_Exception( "Option \"$flag\" is not recognized.", $this->getUsageMessage()); } $realFlag = $this->_ruleMap[$flag]; switch ($this->_rules[$realFlag]['param']) { case 'required': if (count($argv) > 0) { $param = array_shift($argv); $this->_checkParameterType($realFlag, $param); } else { require_once 'Zend/Console/Getopt/Exception.php'; throw new Zend_Console_Getopt_Exception( "Option \"$flag\" requires a parameter.", $this->getUsageMessage()); } break; case 'optional': if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') { $param = array_shift($argv); $this->_checkParameterType($realFlag, $param); } else { $param = true; } break; default: $param = true; } $this->_options[$realFlag] = $param; }
php
{ "resource": "" }
q255636
Zend_Console_Getopt._addRulesModeGnu
test
protected function _addRulesModeGnu($rules) { $ruleArray = array(); /** * Options may be single alphanumeric characters. * Options may have a ':' which indicates a required string parameter. * No long options or option aliases are supported in GNU style. */ preg_match_all('/([a-zA-Z0-9]:?)/', $rules, $ruleArray); foreach ($ruleArray[1] as $rule) { $r = array(); $flag = substr($rule, 0, 1); if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) { $flag = strtolower($flag); } $r['alias'][] = $flag; if (substr($rule, 1, 1) == ':') { $r['param'] = 'required'; $r['paramType'] = 'string'; } else { $r['param'] = 'none'; } $this->_rules[$flag] = $r; $this->_ruleMap[$flag] = $flag; } }
php
{ "resource": "" }
q255637
Zend_Console_Getopt._addRulesModeZend
test
protected function _addRulesModeZend($rules) { foreach ($rules as $ruleCode => $helpMessage) { // this may have to translate the long parm type if there // are any complaints that =string will not work (even though that use // case is not documented) if (in_array(substr($ruleCode, -2, 1), array('-', '='))) { $flagList = substr($ruleCode, 0, -2); $delimiter = substr($ruleCode, -2, 1); $paramType = substr($ruleCode, -1); } else { $flagList = $ruleCode; $delimiter = $paramType = null; } if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) { $flagList = strtolower($flagList); } $flags = explode('|', $flagList); $rule = array(); $mainFlag = $flags[0]; foreach ($flags as $flag) { if (empty($flag)) { require_once 'Zend/Console/Getopt/Exception.php'; throw new Zend_Console_Getopt_Exception( "Blank flag not allowed in rule \"$ruleCode\"."); } if (strlen($flag) == 1) { if (isset($this->_ruleMap[$flag])) { require_once 'Zend/Console/Getopt/Exception.php'; throw new Zend_Console_Getopt_Exception( "Option \"-$flag\" is being defined more than once."); } $this->_ruleMap[$flag] = $mainFlag; $rule['alias'][] = $flag; } else { if (isset($this->_rules[$flag]) || isset($this->_ruleMap[$flag])) { require_once 'Zend/Console/Getopt/Exception.php'; throw new Zend_Console_Getopt_Exception( "Option \"--$flag\" is being defined more than once."); } $this->_ruleMap[$flag] = $mainFlag; $rule['alias'][] = $flag; } } if (isset($delimiter)) { switch ($delimiter) { case self::PARAM_REQUIRED: $rule['param'] = 'required'; break; case self::PARAM_OPTIONAL: default: $rule['param'] = 'optional'; } switch (substr($paramType, 0, 1)) { case self::TYPE_WORD: $rule['paramType'] = 'word'; break; case self::TYPE_INTEGER: $rule['paramType'] = 'integer'; break; case self::TYPE_STRING: default: $rule['paramType'] = 'string'; } } else { $rule['param'] = 'none'; } $rule['help'] = $helpMessage; $this->_rules[$mainFlag] = $rule; } }
php
{ "resource": "" }
q255638
OAuth1.getOAuthHeader
test
public function getOAuthHeader($uri, $queryParameters, $httpMethod){ $this->sign($uri, $queryParameters, $httpMethod); foreach($this->oauthParameters as $k => $v){ $this->oauthParameters[$k] = $k . '="' . rawurlencode($v) . '"'; } return 'OAuth ' . implode(',', $this->oauthParameters); }
php
{ "resource": "" }
q255639
OAuth1.getBaseString
test
public function getBaseString($uri, $method, array $parameters = array()){ $baseString = $this->prepareHttpMethod($method) . '&' . $this->prepareURL($uri) . '&' . $this->prepareQueryParams($parameters); return $baseString; }
php
{ "resource": "" }
q255640
OAuth1.prepareHttpMethod
test
private function prepareHttpMethod($method){ $trimmedMethod = trim($method); $upperMethod = strtoupper($trimmedMethod); return rawurlencode($method); }
php
{ "resource": "" }
q255641
OAuth1.setNonce
test
private function setNonce($length = 6){ $result = ''; $cLength = strlen(self::NONCE_CHARS); for ($i=0; $i < $length; $i++) { $rnum = rand(0,$cLength - 1); $result .= substr(self::NONCE_CHARS,$rnum,1); } $this->oauthNonce = $result; }
php
{ "resource": "" }
q255642
OAuth1.appendOAuthPartsTo
test
private function appendOAuthPartsTo(array $queryParameters = null){ if($queryParameters == null){ $queryParameters = array(); } $queryParameters['oauth_consumer_key'] = $this->consumerKey; $queryParameters['oauth_token'] = $this->oauthToken; $queryParameters['oauth_signature_method'] ='HMAC-SHA1'; $queryParameters['oauth_timestamp'] = $this->oauthTimeStamp; $queryParameters['oauth_nonce'] =$this->oauthNonce; $queryParameters['oauth_version'] = '1.0'; return $queryParameters; }
php
{ "resource": "" }
q255643
QueryMessage.getString
test
public function getString() { if (empty($this->sql) || empty($this->entity)) { return null; } $query = ""; $query .= $this->sql; if (0==count($this->projection)) { $query .= " "."*"; } else { if (count($this->projection)) { $query .= " " . implode(", ", $this->projection); } } $query .= " FROM " . $this->entity; if (!empty($this->whereClause)) { if (count($this->whereClause)) { $query .= " WHERE " . implode(" AND ", $this->whereClause); } } if (!empty($this->orderByClause)) { $query .= " ORDERBY " . $this->orderByClause; } if (!empty($this->startposition)) { $query .= " STARTPOSITION " . $this->startposition; } if (!empty($this->maxresults)) { $query .= " MAXRESULTS " . $this->maxresults; } return $query; }
php
{ "resource": "" }
q255644
ClientFactory.createClient
test
public static function createClient($clientName = CoreConstants::CLIENT_CURL){ if($clientName == CoreConstants::CLIENT_CURL){ if(extension_loaded('curl')){ return new CurlHttpClient(); }else{ throw new SdkException("curl extension is not enabled. Cannot create curl http client for the SDK."); } } if(strcasecmp($clientName, CoreConstants::CLIENT_GUZZLE) == 0 ||strcasecmp($clientName, CoreConstants::CLIENT_GUZZLE_FULL) == 0){ if(class_exists('GuzzleHttp\Client')){ return new GuzzleHttpClient(); }else{ throw new SdkException("guzzle client cannot be found. Cannot create guzzle http client for the SDK."); } } throw new SdkException("The client Name you passed is not supported. Please use either 'curl' or 'guzzle' for the client Name."); }
php
{ "resource": "" }
q255645
LogRequestsToDisk.GetLogDestination
test
public function GetLogDestination() { if ($this->EnableServiceRequestsLogging) { if (false === file_exists($this->ServiceRequestLoggingLocation)) { $this->ServiceRequestLoggingLocation = sys_get_temp_dir(); } } return $this->ServiceRequestLoggingLocation; }
php
{ "resource": "" }
q255646
LogRequestsToDisk.LogPlatformRequests
test
public function LogPlatformRequests($xml, $url, $headers, $isRequest) { if ($this->EnableServiceRequestsLogging) { if (false === file_exists($this->ServiceRequestLoggingLocation)) { $this->ServiceRequestLoggingLocation = sys_get_temp_dir(); } // Use filecount to have some sort of sequence number for debugging purposes - 5 digits $sequenceNumber = iterator_count(new \DirectoryIterator($this->ServiceRequestLoggingLocation)); $sequenceNumber = str_pad((int)$sequenceNumber, 5, "0", STR_PAD_LEFT); $iter = 0; $filePath = null; do { $filePath = null; if ($isRequest) { $filePath = CoreConstants::REQUESTFILENAME_FORMAT; $filePath = str_replace("{0}", $this->ServiceRequestLoggingLocation, $filePath); } else { $filePath = CoreConstants::RESPONSEFILENAME_FORMAT; $filePath = str_replace("{0}", $this->ServiceRequestLoggingLocation, $filePath); } $filePath = str_replace("{1}", CoreConstants::SLASH_CHAR.$sequenceNumber.'-', $filePath); $filePath = str_replace("{2}", time()."-".(int)$iter, $filePath); $iter++; } while (file_exists($filePath)); try { $collapsedHeaders = array(); foreach ($headers as $key=>$val) { $collapsedHeaders[] = "{$key}: {$val}"; } file_put_contents($filePath, ($isRequest?"REQUEST":"RESPONSE")." URI FOR SEQUENCE ID {$sequenceNumber}\n==================================\n{$url}\n\n", FILE_APPEND); file_put_contents($filePath, ($isRequest?"REQUEST":"RESPONSE")." HEADERS\n================\n".implode("\n", $collapsedHeaders)."\n\n", FILE_APPEND); file_put_contents($filePath, ($isRequest?"REQUEST":"RESPONSE")." BODY\n=============\n".$xml."\n\n", FILE_APPEND); } catch (\Exception $e) { throw new IdsException("Exception during LogPlatformRequests."); } } }
php
{ "resource": "" }
q255647
OperationControlList.isAllowed
test
public function isAllowed($entity, $operation) { //fallback to global rules if entity wasn't specified in the rules $lookupEn = array_key_exists($entity, $this->operationList) ? $entity : self::ALL; //fallback to global rules if operation wasn't specified in the rules $lookupOp = array_key_exists($operation, $this->operationList[$lookupEn]) ? $operation : self::ALL; // entity and operation were found as is if (($entity === $lookupEn) && ($operation === $lookupOp)) { return $this->operationList[$lookupEn][$lookupOp]; } //lookup for operation for current entity if it exists if (array_key_exists($lookupOp, $this->operationList[$lookupEn])) { return $this->operationList[$lookupEn][$lookupOp]; } //lookup for operation for current entity if it exists if (array_key_exists($operation, $this->operationList[self::ALL])) { return $this->operationList[self::ALL][$operation]; } //fallback to global entity if (array_key_exists($lookupOp, $this->operationList[self::ALL])) { return $this->operationList[self::ALL][$lookupOp]; } //fall back to global entity and operation return $this->operationList[self::ALL][self::ALL]; }
php
{ "resource": "" }
q255648
AbstractWsdl.prepareReflection
test
private function prepareReflection() { $methods = $this->getClassMethods(); foreach ($methods as $method) { $this->methodsMeta[$method->name] = $this->getMethodIO($method->name); } }
php
{ "resource": "" }
q255649
AbstractWsdl.toXml
test
public function toXml() { if (is_string($this->wsdlXmlSource) && $this->wsdlXmlSource != '') { return $this->wsdlXmlSource; } else { $this->prepareDom(); $this->prepareReflection(); $this->prepare(); $this->wsdlXmlSource = $this->dom->saveXML(); return $this->wsdlXmlSource; } }
php
{ "resource": "" }
q255650
AbstractWsdl.copyToPublic
test
public function copyToPublic($path, $overwrite = false) { $publicPath = realpath($this->getPublicPath()); $targetFilePath = $publicPath.DIRECTORY_SEPARATOR.basename($path); if (($overwrite === true && file_exists($targetFilePath)) || !file_exists($targetFilePath)) { if (!copy($path, $targetFilePath)) { throw new \RuntimeException("Cannot copy ".basename($path)." to ".$publicPath); } } return $targetFilePath; }
php
{ "resource": "" }
q255651
Php2Xml.castToStringZero
test
private function castToStringZero($prop, $obj) { if ($this->isEmptyInt($prop->getValue($obj))) { //reset value in very specific case to keep it intact $prop->setValue($obj, (string) $prop->getValue($obj)); } }
php
{ "resource": "" }
q255652
LocalConfigReader.ReadConfigurationFromFile
test
public static function ReadConfigurationFromFile($filePath, $OAuthOption = CoreConstants::OAUTH1) { $ippConfig = new IppConfiguration(); try { if (isset($filePath) && file_exists($filePath)) { $xmlObj = simplexml_load_file($filePath); } else { // $xmlObj = simplexml_load_file(PATH_SDK_ROOT . 'sdk.config'); throw new \Exception("Can't Read Configuration from file: ". $filePath); } LocalConfigReader::initializeOAuthSettings($xmlObj, $ippConfig, $OAuthOption); LocalConfigReader::initializeRequestAndResponseSerializationAndCompressionFormat($xmlObj, $ippConfig); LocalConfigReader::intializaeServiceBaseURLAndLogger($xmlObj, $ippConfig); LocalConfigReader::initializeAPIEntityRules($xmlObj, $ippConfig); LocalConfigReader::setupMinorVersion($ippConfig, $xmlObj); return $ippConfig; } catch (\Exception $e) { throw new SdkException("Error Reading the "); } }
php
{ "resource": "" }
q255653
LocalConfigReader.initializeAPIEntityRules
test
public static function initializeAPIEntityRules($xmlObj, $ippConfig) { $rules=CoreConstants::getQuickBooksOnlineAPIEntityRules(); LocalConfigReader::initOperationControlList($ippConfig, $rules); $specialConfig = LocalConfigReader::populateJsonOnlyEntities($xmlObj); if (is_array($specialConfig) && ($ippConfig->OpControlList instanceof OperationControlList)) { $ippConfig->OpControlList->appendRules($specialConfig); } }
php
{ "resource": "" }
q255654
LocalConfigReader.populateJsonOnlyEntities
test
public static function populateJsonOnlyEntities($xmlObj) { if (isset($xmlObj) && isset($xmlObj->intuit->ipp->specialConfiguration)) { $specialCnf = $xmlObj->intuit->ipp->specialConfiguration; if (!$specialCnf instanceof SimpleXMLElement) { return false; } if (!$specialCnf->children() instanceof SimpleXMLElement) { return false; } if (!$specialCnf->children()->count()) { return false; } $rules = array(); foreach ($specialCnf->children() as $entity) { if (!$entity->attributes()->count()) { continue; } $name = self::decorateEntity($entity->getName()); if (!array_key_exists($name, $rules)) { $rules[$name] = array(); } foreach ($entity->attributes() as $attr) { $rules[$name][$attr->getName()] = filter_var((string)$entity->attributes(), FILTER_VALIDATE_BOOLEAN); } } return $rules; } return false; }
php
{ "resource": "" }
q255655
LocalConfigReader.initializeOAuthSettings
test
public static function initializeOAuthSettings($xmlObj, $ippConfig, $OAuthOption) { // if it is OAuth1 Settings. if (isset($xmlObj) && isset($xmlObj->intuit->ipp->security) && $OAuthOption == CoreConstants::OAUTH1 && isset($xmlObj->intuit->ipp->security->oauth1)) { try { $currentAccessTokenKey = $xmlObj->intuit->ipp->security->oauth1->attributes()['accessTokenKey']; $currentAccessTokenSecret = $xmlObj->intuit->ipp->security->oauth1->attributes()['accessTokenSecret']; $currentConsumerKey = $xmlObj->intuit->ipp->security->oauth1->attributes()['consumerKey']; $currentConsumerSecret = $xmlObj->intuit->ipp->security->oauth1->attributes()['consumerSecret']; $ippConfig->RealmID = $xmlObj->intuit->ipp->security->oauth1->attributes()['QBORealmID']; $ippConfig->OAuthMode = CoreConstants::OAUTH1; } catch (\Exception $e) { throw new \Exception("Can't Read OAuth1 values from config file."); } $ippConfig->Security = new OAuthRequestValidator($currentAccessTokenKey, $currentAccessTokenSecret, $currentConsumerKey, $currentConsumerSecret); } // OAUth 2 settings if available elseif (isset($xmlObj) && isset($xmlObj->intuit->ipp->security) && $OAuthOption == CoreConstants::OAUTH2 && isset($xmlObj->intuit->ipp->security->oauth2)) { //Implement OAuth 2 parts here // Set SSL check status to be true $ippConfig->SSLCheckStatus = true; $currentOAuth2AccessTokenKey = $xmlObj->intuit->ipp->security->oauth2->attributes()['accessTokenKey']; $currentOAuth2RefreshTokenKey = $xmlObj->intuit->ipp->security->oauth2->attributes()['refreshTokenKey']; $clientID = $xmlObj->intuit->ipp->security->oauth2->attributes()['ClientID']; $clientSecret = $xmlObj->intuit->ipp->security->oauth2->attributes()['ClientSecret']; $ippConfig->RealmID = $xmlObj->intuit->ipp->security->oauth2->attributes()['QBORealmID']; $OAuth2AccessToken = new OAuth2AccessToken($clientID, $clientSecret, $currentOAuth2AccessTokenKey, $currentOAuth2RefreshTokenKey); $ippConfig->Security = $OAuth2AccessToken; $ippConfig->OAuthMode = CoreConstants::OAUTH2; } else { throw new \Exception("Can't load " .$OAuthOption . " config from config file or the OAuth option is not supported."); } }
php
{ "resource": "" }
q255656
LocalConfigReader.initializeRequestAndResponseSerializationAndCompressionFormat
test
public static function initializeRequestAndResponseSerializationAndCompressionFormat($xmlObj, $ippConfig) { LocalConfigReader::intializeMessage($ippConfig); $requestSerializationFormat = null; $requestCompressionFormat = null; $responseSerializationFormat = null; $responseCompressionFormat = null; if (isset($xmlObj) && isset($xmlObj->intuit->ipp->message->request)) { $requestAttr = $xmlObj->intuit->ipp->message->request->attributes(); $requestSerializationFormat = (string)$requestAttr->serializationFormat; $requestCompressionFormat = (string)$requestAttr->compressionFormat; } // Initialize Response Configuration Object if (isset($xmlObj) && isset($xmlObj->intuit->ipp->message->response)) { $responseAttr = $xmlObj->intuit->ipp->message->response->attributes(); $responseSerializationFormat = (string)$responseAttr->serializationFormat; $responseCompressionFormat = (string)$responseAttr->compressionFormat; } LocalConfigReader::setRequestAndResponseSerializationFormat($ippConfig, $requestCompressionFormat, $responseCompressionFormat, $requestSerializationFormat, $responseSerializationFormat); }
php
{ "resource": "" }
q255657
LocalConfigReader.intializaeServiceBaseURLAndLogger
test
public static function intializaeServiceBaseURLAndLogger($xmlObj, $ippConfig) { // Initialize BaseUrl Configuration Object $ippConfig->BaseUrl = new BaseUrl(); if (isset($xmlObj) && isset($xmlObj->intuit->ipp->service->baseUrl)) { $responseAttr = $xmlObj->intuit->ipp->service->baseUrl->attributes(); $ippConfig->BaseUrl->Qbo = (string)$responseAttr->qbo; $ippConfig->BaseUrl->Ipp = (string)$responseAttr->ipp; } else { throw new \Exception("Base Url is not available from Config file."); } // Initialize Logger if (isset($xmlObj) && isset($xmlObj->intuit->ipp->logger->requestLog)) { $requestLogAttr = $xmlObj->intuit->ipp->logger->requestLog->attributes(); $ServiceRequestLoggingLocation = (string)$requestLogAttr->requestResponseLoggingDirectory; $EnableRequestResponseLogging = (string)$requestLogAttr->enableRequestResponseLogging; LocalConfigReader::setupLogger($ippConfig, $ServiceRequestLoggingLocation, $EnableRequestResponseLogging); } else { throw new \Exception("Log settings is not available from Config file."); } // A developer is forced to write in the same style. // This should be refactored if (isset($xmlObj) && isset($xmlObj->intuit->ipp->contentWriter)) { $contentWriterAttr = $xmlObj->intuit->ipp->contentWriter->attributes(); $strategy = ContentWriterSettings::checkStrategy((string)$contentWriterAttr->strategy); $prefix = (string)$contentWriterAttr->prefix; $exportDir = $contentWriterAttr->exportDirectory; $returnOject = $contentWriterAttr->returnObject; LocalConfigReader::setupContentWriter($ippConfig, $strategy, $prefix, $exportDir, $returnOject); } else { throw new \Exception("Content Writer Settings is not available from Config file."); } }
php
{ "resource": "" }
q255658
IntuitCDCResponse.getEntity
test
public function getEntity($key) { foreach ($this->entities as $entityKey => $entityVal) { if ($entityKey==$key) { return $entityVal; } } return null; }
php
{ "resource": "" }
q255659
IntuitErrorHandler.IsValidXml
test
public static function IsValidXml($inputString) { if (0!==strpos($inputString, '<')) { return false; } try { $doc = simplexml_load_string($inputString); } catch (\Exception $e) { return false; } return true; }
php
{ "resource": "" }
q255660
ContentWriterSettings.verifyConfiguration
test
public function verifyConfiguration() { if (($this->strategy === CoreConstants::EXPORT_STRATEGY) && !empty($this->strategy)) { if (is_null($this->exportDir)) { throw new SdkException("Invalid value for exportDirectory property. It can not be null with 'export' strategy. "); } //clear file cache clearstatcache(); if (!file_exists($this->exportDir)) { throw new SdkException("Directory ({$this->exportDir}) doesn't exist."); } if (!is_dir($this->exportDir)) { throw new SdkException("Path ({$this->exportDir}) isn't a valid directory"); } if (!is_writable($this->exportDir)) { throw new SdkException("Directory ({$this->exportDir}) isn't writable"); } } }
php
{ "resource": "" }
q255661
ReflectionUtil.loadWebServicesClassAndReturnNames
test
public static function loadWebServicesClassAndReturnNames($dir = null) { if ($dir == null) { $dir = dirname(__DIR__) . DIRECTORY_SEPARATOR . UtilityConstants::WEBHOOKSDIR; } $webhooksClassNames = array(); foreach (glob("{$dir}/*.php") as $fileName) { require_once($fileName); //get class name $className = substr($fileName, strrpos($fileName, '/') + 1); //remove extension $classNameWithoutExtension = preg_replace('/\\.[^.\\s]{3,4}$/', '', $className); array_push($webhooksClassNames, $classNameWithoutExtension); } return $webhooksClassNames; }
php
{ "resource": "" }
q255662
ReflectionUtil.isValidWebhooksClass
test
public static function isValidWebhooksClass($className, $classCollection = null) { if (!isset($classCollection)) { $classCollection = ReflectionUtil::loadWebServicesClassAndReturnNames(); } if (!isset($className) || trim($className) === '') { return null; } $singlerClassName = ClassNamingUtil::singularize($className); $capitalFirstSinglerClassName = ucfirst($singlerClassName); foreach ($classCollection as $k => $v) { if (strcmp($capitalFirstSinglerClassName, $v) == 0) { return $capitalFirstSinglerClassName; } } return null; }
php
{ "resource": "" }
q255663
Zend_Soap_Server.getOptions
test
public function getOptions() { $options = array(); if (null !== $this->_actor) { $options['actor'] = $this->_actor; } if (null !== $this->_classmap) { $options['classmap'] = $this->_classmap; } if (null !== $this->_encoding) { $options['encoding'] = $this->_encoding; } if (null !== $this->_soapVersion) { $options['soap_version'] = $this->_soapVersion; } if (null !== $this->_uri) { $options['uri'] = $this->_uri; } if (null !== $this->_features) { $options['features'] = $this->_features; } if (null !== $this->_wsdlCache) { $options['cache_wsdl'] = $this->_wsdlCache; } return $options; }
php
{ "resource": "" }
q255664
Zend_Soap_Server.validateUrn
test
public function validateUrn($urn) { $scheme = parse_url($urn, PHP_URL_SCHEME); if ($scheme === false || $scheme === null) { require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception('Invalid URN'); } return true; }
php
{ "resource": "" }
q255665
Zend_Soap_Server.addFunction
test
public function addFunction($function, $namespace = '') { // Bail early if set to SOAP_FUNCTIONS_ALL if ($this->_functions == SOAP_FUNCTIONS_ALL) { return $this; } if (is_array($function)) { foreach ($function as $func) { if (is_string($func) && function_exists($func)) { $this->_functions[] = $func; } else { require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception('One or more invalid functions specified in array'); } } $this->_functions = array_merge($this->_functions, $function); } elseif (is_string($function) && function_exists($function)) { $this->_functions[] = $function; } elseif ($function == SOAP_FUNCTIONS_ALL) { $this->_functions = SOAP_FUNCTIONS_ALL; } else { require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception('Invalid function specified'); } if (is_array($this->_functions)) { $this->_functions = array_unique($this->_functions); } return $this; }
php
{ "resource": "" }
q255666
Zend_Soap_Server.setClass
test
public function setClass($class, $namespace = '', $argv = null) { if (isset($this->_class)) { require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception('A class has already been registered with this soap server instance'); } if (!is_string($class)) { require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception('Invalid class argument (' . gettype($class) . ')'); } if (!class_exists($class)) { require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception('Class "' . $class . '" does not exist'); } $this->_class = $class; if (1 < func_num_args()) { $argv = func_get_args(); array_shift($argv); $this->_classArgs = $argv; } return $this; }
php
{ "resource": "" }
q255667
Zend_Soap_Server.setObject
test
public function setObject($object) { if (!is_object($object)) { require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception('Invalid object argument ('.gettype($object).')'); } if (isset($this->_object)) { require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception('An object has already been registered with this soap server instance'); } $this->_object = $object; return $this; }
php
{ "resource": "" }
q255668
Zend_Soap_Server.getFunctions
test
public function getFunctions() { $functions = array(); if (null !== $this->_class) { $functions = get_class_methods($this->_class); } elseif (null !== $this->_object) { $functions = get_class_methods($this->_object); } return array_merge((array) $this->_functions, $functions); }
php
{ "resource": "" }
q255669
Zend_Soap_Server.setPersistence
test
public function setPersistence($mode) { if (!in_array($mode, array(SOAP_PERSISTENCE_SESSION, SOAP_PERSISTENCE_REQUEST))) { require_once 'Zend/Soap/Server/Exception.php'; throw new Zend_Soap_Server_Exception('Invalid persistence mode specified'); } $this->_persistence = $mode; return $this; }
php
{ "resource": "" }
q255670
Zend_Soap_Server._getSoap
test
protected function _getSoap() { $options = $this->getOptions(); $server = new SoapServer($this->_wsdl, $options); if (!empty($this->_functions)) { $server->addFunction($this->_functions); } if (!empty($this->_class)) { $args = $this->_classArgs; array_unshift($args, $this->_class); call_user_func_array(array($server, 'setClass'), $args); } if (!empty($this->_object)) { $server->setObject($this->_object); } if (null !== $this->_persistence) { $server->setPersistence($this->_persistence); } return $server; }
php
{ "resource": "" }
q255671
Zend_Soap_Server.handle
test
public function handle($request = null) { if (null === $request) { $request = file_get_contents('php://input'); } // Set Zend_Soap_Server error handler $displayErrorsOriginalState = $this->_initializeSoapErrorContext(); $setRequestException = null; /** * @see Zend_Soap_Server_Exception */ require_once 'Zend/Soap/Server/Exception.php'; try { $this->_setRequest($request); } catch (Zend_Soap_Server_Exception $e) { $setRequestException = $e; } $soap = $this->_getSoap(); ob_start(); if ($setRequestException instanceof Exception) { // Send SOAP fault message if we've catched exception $soap->fault("Sender", $setRequestException->getMessage()); } else { try { $soap->handle($request); } catch (\Exception $e) { $fault = $this->fault($e); $soap->fault($fault->faultcode, $fault->faultstring); } } $this->_response = ob_get_clean(); // Restore original error handler restore_error_handler(); ini_set('display_errors', $displayErrorsOriginalState); if (!$this->_returnResponse) { echo $this->_response; return; } return $this->_response; }
php
{ "resource": "" }
q255672
Zend_Soap_Server.deregisterFaultException
test
public function deregisterFaultException($class) { if (in_array($class, $this->_faultExceptions, true)) { $index = array_search($class, $this->_faultExceptions); unset($this->_faultExceptions[$index]); return true; } return false; }
php
{ "resource": "" }
q255673
Zend_Soap_Server.fault
test
public function fault($fault = null, $code = "Receiver") { if ($fault instanceof Exception) { $class = get_class($fault); if (in_array($class, $this->_faultExceptions)) { $message = $fault->getMessage(); $eCode = $fault->getCode(); $code = empty($eCode) ? $code : $eCode; } else { $message = 'Unknown error'; } } elseif (is_string($fault)) { $message = $fault; } else { $message = 'Unknown error'; } $allowedFaultModes = array( 'VersionMismatch', 'MustUnderstand', 'DataEncodingUnknown', 'Sender', 'Receiver', 'Server' ); if (!in_array($code, $allowedFaultModes)) { $code = "Receiver"; } return new SoapFault($code, $message); }
php
{ "resource": "" }
q255674
Zend_Soap_Server.handlePhpErrors
test
public function handlePhpErrors($errno, $errstr, $errfile = null, $errline = null, array $errcontext = null) { throw $this->fault($errstr, "Receiver"); }
php
{ "resource": "" }
q255675
OAuth2LoginHelper.getAccessToken
test
public function getAccessToken(){ if(isset($this->oauth2AccessToken) && !empty($this->oauth2AccessToken)){ return $this->oauth2AccessToken; }else{ throw new SdkException("Can't get OAuth 2 Access Token Object. It is not set yet."); } }
php
{ "resource": "" }
q255676
OAuth2LoginHelper.getAuthorizationCodeURL
test
public function getAuthorizationCodeURL(){ $parameters = array( 'client_id' => $this->getClientID(), 'scope' => $this->getScope(), 'redirect_uri' => $this->getRedirectURL(), 'response_type' => 'code', 'state' => $this->getState() ); $authorizationRequestUrl = CoreConstants::OAUTH2_AUTHORIZATION_REQUEST_URL; $authorizationRequestUrl .= '?' . http_build_query($parameters, null, '&', PHP_QUERY_RFC1738); return $authorizationRequestUrl; }
php
{ "resource": "" }
q255677
OAuth2LoginHelper.refreshToken
test
public function refreshToken(){ $refreshToken = $this->getAccessToken()->getRefreshToken(); $http_header = $this->constructRefreshTokenHeader(); $requestBody = $this->constructRefreshTokenBody($refreshToken); $intuitResponse = $this->curlHttpClient->makeAPICall(CoreConstants::OAUTH2_TOKEN_ENDPOINT_URL, CoreConstants::HTTP_POST, $http_header, $requestBody, null, true); $this->faultHandler = $intuitResponse->getFaultHandler(); if($this->faultHandler) { throw new ServiceException("Refresh OAuth 2 Access token with Refresh Token failed. Body: [" . $this->faultHandler->getResponseBody() . "].", $this->faultHandler->getHttpStatusCode()); }else{ $this->faultHandler = false; $this->oauth2AccessToken = $this->parseNewAccessTokenFromResponse($intuitResponse->getBody()); return $this->getAccessToken(); } }
php
{ "resource": "" }
q255678
OAuth2LoginHelper.OAuth1ToOAuth2Migration
test
public function OAuth1ToOAuth2Migration($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret, $scope){ $oauth1Encrypter = new OAuth1($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret); $parameters = array( 'scope' => $scope, 'redirect_uri' => "https://developer.intuit.com/v2/OAuth2Playground/RedirectUrl", 'client_id' => $this->getClientID(), 'client_secret' => $this->getClientSecret() ); $baseURL = "https://developer.api.intuit.com/v2/oauth2/tokens/migrate"; $authorizationHeaderInfo = $oauth1Encrypter->getOAuthHeader($baseURL, array(), "POST"); $http_header = array( 'Accept' => 'application/json', 'Authorization' => $authorizationHeaderInfo, 'Content-Type' => 'application/json' ); $intuitResponse = $this->curlHttpClient->makeAPICall($baseURL, CoreConstants::HTTP_POST, $http_header, json_encode($parameters), null, false); $this->faultHandler = $intuitResponse->getFaultHandler(); if($this->faultHandler) { throw new ServiceException("Migrate OAuth 1 token to OAuth 2 token failed. Body: [" . $this->faultHandler->getResponseBody() . "].", $this->faultHandler->getHttpStatusCode()); }else{ $this->faultHandler = false; $this->oauth2AccessToken = $this->parseNewAccessTokenFromResponse($intuitResponse->getBody()); return $this->getAccessToken(); } }
php
{ "resource": "" }
q255679
OAuth2LoginHelper.parseNewAccessTokenFromResponse
test
private function parseNewAccessTokenFromResponse($body, $realmID = null){ if(is_string($body)){ $json_body = json_decode($body, true); if(json_last_error() === JSON_ERROR_NONE){ $tokenExpiresTime = $json_body[CoreConstants::EXPIRES_IN]; $refreshToken = $json_body[CoreConstants::OAUTH2_REFRESH_GRANTYPE]; $refreshTokenExpiresTime = $json_body[CoreConstants::X_REFRESH_TOKEN_EXPIRES_IN]; $accessToken = $json_body[CoreConstants::ACCESS_TOKEN]; $this->checkIfEmptyValueReturned($tokenExpiresTime, $refreshToken, $refreshTokenExpiresTime, $accessToken); //If we have a response of OAuth 2 Access Token and the access token is not set, it must come from initial request. Create a dummy access token and update it. if(!isset($this->oauth2AccessToken)){ $this->oauth2AccessToken = new OAuth2AccessToken($this->getClientID(), $this->getClientSecret()); } $this->oauth2AccessToken->updateAccessToken($tokenExpiresTime, $refreshToken, $refreshTokenExpiresTime, $accessToken); if(isset($realmID)){ $this->oauth2AccessToken->setRealmID($realmID); } return $this->oauth2AccessToken; }else{ throw new SdkException("JSON DECODE encounters error:" . json_last_error()); } } }
php
{ "resource": "" }
q255680
OAuth2LoginHelper.checkIfEmptyValueReturned
test
private function checkIfEmptyValueReturned($tokenExpiresTime, $refreshToken, $refreshTokenExpiresTime, $accessToken){ if(empty($tokenExpiresTime)){ throw new SdkException("Error Retrieve RefreshToken from Response. Token Expires In Time is Empty."); } if(empty($refreshToken)){ throw new SdkException("Error Retrieve RefreshToken from Response. Refresh Token is Empty."); } if(empty($refreshTokenExpiresTime)){ throw new SdkException("Error Retrieve RefreshToken from Response. Refresh Token Expires Time is Empty."); } if(empty($accessToken)){ throw new SdkException("Error Retrieve RefreshToken from Response. Access Token is Empty."); } }
php
{ "resource": "" }
q255681
OAuth2LoginHelper.generateAuthorizationHeader
test
private function generateAuthorizationHeader(){ $encodedClientIDClientSecrets = base64_encode($this->getClientID() . ':' . $this->getClientSecret()); $authorizationheader = CoreConstants::OAUTH2_AUTHORIZATION_TYPE . $encodedClientIDClientSecrets; return $authorizationheader; }
php
{ "resource": "" }
q255682
OAuth2LoginHelper.constructRefreshTokenHeader
test
private function constructRefreshTokenHeader(){ $authorizationHeaderInfo = $this->generateAuthorizationHeader(); $http_header = array( 'Accept' => CoreConstants::CONTENTTYPE_APPLICATIONJSON, 'Authorization' => $authorizationHeaderInfo, 'Content-Type' => CoreConstants::CONTENTTYPE_URLFORMENCODED, 'connection' => 'close' ); return $http_header; }
php
{ "resource": "" }
q255683
JsonObjectSerializer.checkResult
test
private function checkResult($result) { $this->lastError = json_last_error(); if (JSON_ERROR_NONE !== $this->lastError) { IdsExceptionManager::HandleException($this->getMessageFromErrorCode($this->lastError)); } //TODO add logger here return $result; }
php
{ "resource": "" }
q255684
JsonObjectSerializer.getMessageFromErrorCode
test
private function getMessageFromErrorCode($error) { if (function_exists('json_last_error_msg')) { return json_last_error_msg(); } $errors = array( JSON_ERROR_NONE => null, JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded' ); return array_key_exists($error, $errors) ? $errors[$error] : "Unknown error ({$error})"; }
php
{ "resource": "" }
q255685
JsonObjectSerializer.convertObject
test
private function convertObject($object, $limitToOne) { if ($object instanceof \stdClass) { $result = array(); $vars = get_object_vars($object); if (empty($vars)) { return null; } foreach ($vars as $key=>$value) { $className = self::decorateIntuitEntityToPhpClassName($key); if (!class_exists($className)) { continue; } $entity = DomainEntityBuilder::create($className, $value); if ($limitToOne) { return $entity; } $result[] = $entity; } if (empty($result)) { // Reutrn original parsed object and don't try to convert types return $limitToOne ? $object : array($object); } else { return $result; } } return $object; }
php
{ "resource": "" }
q255686
JsonObjectSerializer.Serialize
test
public function Serialize($entity) { $this->collectResourceURL($entity); $arrayObj = $this->customerConvertObjectToArray($entity); $array = $this->removeNullProperties($arrayObj); return $this->checkResult(json_encode($array, true)); }
php
{ "resource": "" }
q255687
JsonObjectSerializer.removeNullProperties
test
private function removeNullProperties($val){ $filterArray = array_filter($val); $returned = array(); foreach($filterArray as $k => $v){ if(is_array($v)){ if(FacadeHelper::isRecurrsiveArray($v)){ $list = array(); foreach($v as $kk => $vv){ $list[] = array_filter($vv); } $returned[$k] = $list; } }else{ $returned[$k] = $v; } } return $returned; }
php
{ "resource": "" }
q255688
Zend_Soap_Wsdl_Strategy_DefaultComplexType.addComplexType
test
public function addComplexType($type) { if (!class_exists($type)) { require_once "Zend/Soap/Wsdl/Exception.php"; throw new Zend_Soap_Wsdl_Exception(sprintf( "Cannot add a complex type %s that is not an object or where ". "class could not be found in 'DefaultComplexType' strategy.", $type )); } $dom = $this->getContext()->toDomDocument(); $class = new ReflectionClass($type); $complexType = $dom->createElement('xsd:complexType'); $complexType->setAttribute('name', $type); $all = $dom->createElement('xsd:all'); foreach ($class->getProperties() as $property) { if ($property->isPublic() && preg_match_all('/@var\s+([^\s]+)/m', $property->getDocComment(), $matches)) { /** * @todo check if 'xsd:element' must be used here (it may not be compatible with using 'complexType' * node for describing other classes used as attribute types for current class */ $element = $dom->createElement('xsd:element'); $element->setAttribute('name', $property->getName()); $element->setAttribute('type', $this->getContext()->getType(trim($matches[1][0]))); $all->appendChild($element); } } $complexType->appendChild($all); $this->getContext()->getSchema()->appendChild($complexType); $this->getContext()->addType($type); return "tns:$type"; }
php
{ "resource": "" }
q255689
Wsdl.getWsdl
test
public function getWsdl($class = null) { /* if ($class != null) { $this->class = $class; } elseif ($this->class == null) { throw new \RuntimeException("No class defined"); } if (!is_object($this->class) && !is_string($this->class)) { throw new \RuntimeException("Given class is neither class nor string"); } if (is_string($this->class)) { if (!class_exists($this->class)) { throw new \RuntimeException("Class ".$class." is not found. Did you forget to include it?"); } $this->class = new $this->class(); } */ //$this->refl = new \ReflectionClass($this->class); //$this->wsdl = new \Zend_Soap_Wsdl($this->refl->getShortName(), // $this->namespaceToUrn($this->refl->getNamespaceName())); $factory = new wsdl\WsdlFactory($class, wsdl\WsdlFactory::WSDL_1_1); $this->wsdl = $factory->getImplementation(); $this->wsdl->debug = true; /* $this->addTypes(); $this->addMessages(); $this->addPortType(); $this->addBindings(); $this->addServices(); $dom = $this->wsdl->toDomDocument(); if ($this->debug) { $dom->formatOutput = true; }*/ return $this->wsdl->toXml();//$dom->saveXml(); }
php
{ "resource": "" }
q255690
Wsdl.addBindings
test
private function addBindings() { $this->binding = $this->wsdl->addBinding($this->refl->getShortName().$this->bindingNameSuffix, $this->targetNsPrefix.":".$this->getBindingTypeName()); $this->wsdl->addSoapBinding($this->binding, $this->getSoapBindingStyle(), $this->getSoapBindingTransport()); $this->addBindingOperations(); return $this->binding; }
php
{ "resource": "" }
q255691
Wsdl.addPortType
test
private function addPortType() { $this->portType = $this->wsdl->addPortType($this->getPortName()); $this->addPortOperations(); return $this->portType; }
php
{ "resource": "" }
q255692
Wsdl.addTypes
test
public function addTypes() { $methods = $this->getClassMethods(); foreach ($methods as $method) { $data = $this->getMethodIO($method->name); $element = array('name' => $method->name, 'sequence' => array() ); if (array_key_exists("params", $data)) { foreach ($data['params'] as $param) { if ($this->isLocalType($this->getTypeName($param['type']))) { array_push($element['sequence'], array('name' => $param['name'], 'type' => $this->getTypeName($param['type']))); } else { array_push($element['sequence'], array('ref' => $this->getTypeName($param['type']))); } } $this->wsdl->addElement($element); } if (array_key_exists("return", $data)) { $return = ""; if ($this->isLocalType($this->getTypeName($data['return']['type']))) { $return = array('name' => $method->name.$this->responseSuffix, 'sequence' => array(array('name' => 'Response', 'type' => $this->getTypeName($data['return']['type'])))); } else { $return = array('name' => $method->name.$this->responseSuffix, 'sequence' => array(array('ref' => $this->getTypeName($data['return']['type'])))); } $this->wsdl->addElement($return); } } }
php
{ "resource": "" }
q255693
Wsdl.addBindingOperations
test
public function addBindingOperations() { $methods = $this->getClassMethods(); //@todo Check if binding is instantiated foreach ($methods as $method) { $data = $this->getMethodIO($method->name); $bindingInput = false; $bindingOutput = false; if (array_key_exists("params", $data)) { $bindingInput = array('use' => 'literal'); } if (array_key_exists("return", $data)) { $bindingOutput = array('use' => 'literal'); } $operation = $this->wsdl->addBindingOperation($this->binding, $method->name, $bindingInput, $bindingOutput); $soapOperation = $this->wsdl->addSoapOperation($operation, $this->namespaceToUrn($this->refl->getNamespaceName())."/".$method->name); } }
php
{ "resource": "" }
q255694
Wsdl.addPortOperations
test
private function addPortOperations() { $methods = $this->getClassMethods(); foreach ($methods as $method) { $data = $this->getMethodIO($method->name); $input = false; $output = false; $bindingInput = false; $bindingOutput = false; if (array_key_exists("params", $data)) { $input = $this->targetNsPrefix.":".$method->name.$this->requestSuffix; } if (array_key_exists("return", $data)) { $output = $this->targetNsPrefix.":".$method->name.$this->responseSuffix; } $this->wsdl->addPortOperation($this->portType, $method->name, $input, $output); } }
php
{ "resource": "" }
q255695
Wsdl.isLocalType
test
public function isLocalType($type) { if (preg_match('/:/', $type)) { list($ns, $typeName) = explode(":", $type); if ($ns == $this->targetNsPrefix || $ns == $this->xmlSchemaPreffix) { return true; // Local type } else { return false; } } else { // @todo - No namespace - local type return true; } }
php
{ "resource": "" }
q255696
Wsdl.addServices
test
private function addServices() { $this->wsdl->addService($this->getServiceName(), $this->getPortName(), $this->getBindingName(), $this->getLocation()); }
php
{ "resource": "" }
q255697
Xsd2Php.getTargetNS
test
private function getTargetNS($xpath) { $query = "//*[local-name()='schema' and namespace-uri()='http://www.w3.org/2001/XMLSchema']/@targetNamespace"; $targetNs = $xpath->query($query); if ($targetNs) { foreach ($targetNs as $entry) { return $entry->nodeValue; } } }
php
{ "resource": "" }
q255698
Xsd2Php.getNamespaces
test
public function getNamespaces($xpath) { $query = "//namespace::*"; $entries = $xpath->query($query); $nspaces = array(); foreach ($entries as $entry) { if ($entry->nodeValue == "http://www.w3.org/2001/XMLSchema") { $this->xsdNs = preg_replace('/xmlns:(.*)/', "$1", $entry->nodeName); } if (//$entry->nodeName != $this->xsdNs //&& $entry->nodeName != 'xmlns:xml') { if (preg_match('/:/', $entry->nodeName)) { $nodeName = explode(':', $entry->nodeName); $nspaces[$nodeName[1]] = $entry->nodeValue; } else { $nspaces[$entry->nodeName] = $entry->nodeValue; } } } return $nspaces; }
php
{ "resource": "" }
q255699
Xsd2Php.saveClasses
test
public function saveClasses($dir, $createDirectory = false) { $this->setXmlSource($this->getXML()->saveXML()); $this->savePhpFiles($dir, $createDirectory); }
php
{ "resource": "" }