_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q255700 | Xsd2Php.loadIncludes | test | public function loadIncludes($dom, $filepath = '', $namespace = '')
{
$xpath = new \DOMXPath($dom);
$query = "//*[local-name()='include' and namespace-uri()='http://www.w3.org/2001/XMLSchema']";
$includes = $xpath->query($query);
foreach ($includes as $entry) {
$parent = $entry->parentNode;
$xsd = new \DOMDocument();
$xsdFileName = realpath($filepath.DIRECTORY_SEPARATOR.$entry->getAttribute("schemaLocation"));
if ($this->debug) {
print('Including '.$xsdFileName."\n");
}
if (!file_exists($xsdFileName)) {
if ($this->debug) {
print $xsdFileName. " is not found \n";
}
continue;
}
$result = $xsd->load($xsdFileName,
LIBXML_DTDLOAD|LIBXML_DTDATTR|LIBXML_NOENT|LIBXML_XINCLUDE);
if ($result) {
$mxpath = new \DOMXPath($xsd);
$this->shortNamespaces = array_merge($this->shortNamespaces, $this->getNamespaces($mxpath));
}
foreach ($xsd->documentElement->childNodes as $node) {
if ($node->nodeName == $this->xsdNs.":include") {
$loc = realpath($filepath.DIRECTORY_SEPARATOR.$node->getAttribute('schemaLocation'));
$node->setAttribute('schemaLocation', $loc);
if ($this->debug) {
print('Change included schema location to '.$loc." \n");
}
$newNode = $dom->importNode($node, true);
$parent->insertBefore($newNode, $entry);
} else {
if ($namespace != '') {
$newNodeNs = $xsd->createAttribute("namespace");
$textEl = $xsd->createTextNode($namespace);
$newNodeNs->appendChild($textEl);
$node->appendChild($newNodeNs);
}
$newNode = $dom->importNode($node, true);
$parent->insertBefore($newNode, $entry);
}
}
$parent->removeChild($entry);
}
/* $xpath = new \DOMXPath($dom);
$query = "//*[local-name()='include' and namespace-uri()='http://www.w3.org/2001/XMLSchema']";
$includes = $xpath->query($query);
if ($includes->length != 0) {
$dom = $this->loadIncludes($dom);
} */
if ($this->debug) {
print_r("\n------------------------------------\n");
}
return $dom;
} | php | {
"resource": ""
} |
q255701 | Xsd2Php.getXML | test | public function getXML()
{
try {
$xsl = new \XSLTProcessor();
$xslDom = new \DOMDocument();
$xslDom->load(dirname(__FILE__) . "/xsd2php2.xsl");
$xsl->registerPHPFunctions();
$xsl->importStyleSheet($xslDom);
$dom = $xsl->transformToDoc($this->dom);
$dom->formatOutput = true;
return $dom;
} catch (\Exception $e) {
throw new \Exception(
"Error interpreting XSD document (".$e->getMessage().")");
}
} | php | {
"resource": ""
} |
q255702 | Xsd2Php.savePhpFiles | test | private function savePhpFiles($dir, $createDirectory = false)
{
if (!file_exists($dir) && $createDirectory === false) {
throw new \RuntimeException($dir." does not exist");
}
if (!file_exists($dir) && $createDirectory === true) {
//@todo Implement Recursive mkdir
mkdir($dir, 0777, true);
}
$classes = $this->getPHP();
foreach ($classes as $fullkey => $value) {
$keys = explode("|", $fullkey);
$key = $keys[0];
$namespace = $this->namespaceToPath($keys[1]);
if ($this->overrideAsSingleNamespace) {
$targetDir = $dir;
} else {
$targetDir = $dir.DIRECTORY_SEPARATOR.$namespace;
}
if (!file_exists($targetDir)) {
mkdir($targetDir, 0777, true);
}
file_put_contents($targetDir.DIRECTORY_SEPARATOR.$key.'.php', $value);
}
if ($this->debug) {
echo "Generated classes saved to ".$dir;
}
} | php | {
"resource": ""
} |
q255703 | Xsd2Php.namespaceToPhp | test | public function namespaceToPhp($xmlNS)
{
$ns = $xmlNS;
$ns = $this->expandNS($ns);
if (preg_match('/urn:/', $ns)) {
//@todo check if there are any components of namespace which are
$ns = preg_replace('/-/', '_', $ns);
$ns = preg_replace('/urn:/', '', $ns);
$ns = preg_replace('/:/', '\\', $ns);
}
/**
if (preg_match('/http:\/\//', $ns)) {
$ns = preg_replace('/http:\/\//', '', $ns);
$ns = preg_replace('/\//','\\', $ns);
$ns = preg_replace('/\./', '\\',$ns);
}*/
$matches = array();
if (preg_match("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#", $ns, $matches)) {
$elements = explode("/", $matches[3]);
$domain = $elements[0];
array_shift($elements);
//print_r($domain."\n");
$ns = implode("\\", array_reverse(explode(".", $domain)));
//$ns = preg_replace('/\./', '\\', );
//print $ns."\n";
foreach ($elements as $key => $value) {
if ($value != '') {
$value = preg_replace('/\./', '_', $value);
$ns .= "\\" . $value;
}
}
}
$ns = explode('\\', $ns);
$i = 0;
foreach ($ns as $elem) {
if (preg_match('/^([0-9]+)(.*)$/', $elem)) {
$ns[$i] = "_".$elem;
}
if (in_array($elem, $this->reservedWords)) {
$ns[$i] = "_".$elem;
}
$i++;
}
$ns = implode('\\', $ns);
return $ns;
} | php | {
"resource": ""
} |
q255704 | OAuth2AccessToken.setBaseURL | test | public function setBaseURL($baseURL){
if(strcasecmp($baseURL, CoreConstants::DEVELOPMENT_SANDBOX) == 0){
$this->baseURL = CoreConstants::SANDBOX_DEVELOPMENT;
}else if(strcasecmp($baseURL, CoreConstants::PRODUCTION_QBO) == 0){
$this->baseURL = CoreConstants::QBO_BASEURL;
}else{
$this->baseURL = $baseURL;
}
} | php | {
"resource": ""
} |
q255705 | OAuth2AccessToken.getRefreshTokenValidationPeriodInSeconds | test | public function getRefreshTokenValidationPeriodInSeconds(){
if(isset($this->refreshTokenValidationPeriod) && !empty($this->refreshTokenValidationPeriod))
{
return $this->refreshTokenValidationPeriod;
}else{
throw new SdkException("The validation period for OAuth 2 refresh Token is not set.");
}
} | php | {
"resource": ""
} |
q255706 | OAuth2AccessToken.getAccessTokenValidationPeriodInSeconds | test | public function getAccessTokenValidationPeriodInSeconds(){
if(isset($this->accessTokenValidationPeriod) && !empty($this->accessTokenValidationPeriod))
{
return $this->accessTokenValidationPeriod;
}else{
throw new SdkException("The validation period for OAuth 2 access Token is not set.");
}
} | php | {
"resource": ""
} |
q255707 | OAuth2AccessToken.getRefreshToken | test | public function getRefreshToken(){
if(isset($this->refresh_token) && !empty($this->refresh_token)) return $this->refresh_token;
else throw new SdkException("The OAuth 2 Refresh Token is not set in the Access Token Object.");
} | php | {
"resource": ""
} |
q255708 | OAuth2AccessToken.getAccessToken | test | public function getAccessToken(){
if(isset($this->accessTokenKey) && !empty($this->accessTokenKey)) return $this->accessTokenKey;
else throw new SdkException("The OAuth 2 Access Token is not set in the Access Token Object.");
} | php | {
"resource": ""
} |
q255709 | OAuth2AccessToken.updateAccessToken | test | public function updateAccessToken($tokenExpiresTime, $refreshToken, $refreshTokenExpiresTime, $accessToken){
$this->setAccessToken($accessToken);
$this->setRefreshToken($refreshToken);
$this->setAccessTokenValidationPeriodInSeconds($tokenExpiresTime);
$this->setRefreshTokenValidationPeriodInSeconds($refreshTokenExpiresTime);
$this->setAccessTokenExpiresAt(time() + $tokenExpiresTime);
$this->setRefreshTokenExpiresAt(time() + $refreshTokenExpiresTime);
} | php | {
"resource": ""
} |
q255710 | XmlObjectSerializer.getPostXmlFromArbitraryEntity | test | public static function getPostXmlFromArbitraryEntity($entity, &$urlResource)
{
if (null==$entity) {
return false;
}
$xmlElementName = XmlObjectSerializer::cleanPhpClassNameToIntuitEntityName(get_class($entity));
$xmlElementName = trim($xmlElementName);
$urlResource = strtolower($xmlElementName);
$httpsPostBody = XmlObjectSerializer::getXmlFromObj($entity);
return $httpsPostBody;
} | php | {
"resource": ""
} |
q255711 | XmlObjectSerializer.PhpObjFromXml | test | private static function PhpObjFromXml($className, $xmlStr)
{
$className = trim($className);
if (class_exists($className, CoreConstants::USE_AUTOLOADER)) {
$phpObj = new $className;
} elseif (class_exists(CoreConstants::NAMEPSACE_DATA_PREFIX . $className, CoreConstants::USE_AUTOLOADER)) {
$className = CoreConstants::NAMEPSACE_DATA_PREFIX . $className;
$phpObj = new $className;
} else {
throw new \Exception("Can't find corresponding CLASS for className" . $className . "during unmarshall XML into POPO Object");
}
$bind = new Bind(CoreConstants::PHP_CLASS_PREFIX);
$bind->overrideAsSingleNamespace='http://schema.intuit.com/finance/v3';
$bind->bindXml($xmlStr, $phpObj);
return $phpObj;
} | php | {
"resource": ""
} |
q255712 | XmlObjectSerializer.ParseArbitraryResultObjects | test | private static function ParseArbitraryResultObjects($responseXml, $bLimitToOne)
{
if (!$responseXml) {
return null;
}
$resultObject = null;
$resultObjects = null;
$responseXmlObj = simplexml_load_string($responseXml);
foreach ($responseXmlObj as $oneXmlObj) {
$oneXmlElementName = (string)$oneXmlObj->getName();
//The handling falut here is a little too simple. add more support for future
//@hao
if ('Fault'==$oneXmlElementName) {
return null;
}
$phpClassName = XmlObjectSerializer::decorateIntuitEntityToPhpClassName($oneXmlElementName);
$onePhpObj = XmlObjectSerializer::PhpObjFromXml($phpClassName, $oneXmlObj->asXML());
$resultObject = $onePhpObj;
$resultObjects[] = $onePhpObj;
// Caller may be anticipating ONLY one object in result
if ($bLimitToOne) {
break;
}
}
if ($bLimitToOne) {
return $resultObject;
} else {
return $resultObjects;
}
} | php | {
"resource": ""
} |
q255713 | BaseCurl.setupOption | test | public function setupOption($k, $v){
if($this->isCurlSet()){
curl_setopt($this->curl, $k, $v);
} else {
throw new SdkException("cURL instance is not set when calling setup Option.");
}
} | php | {
"resource": ""
} |
q255714 | BaseCurl.versionOfTLS | test | public function versionOfTLS(){
$tlsVersion = "";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://www.howsmyssl.com/a/check");
curl_setopt($curl, CURLOPT_SSLVERSION, 6);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curlVersionResponse = curl_exec($curl);
if($curlVersionResponse === false){
throw new SdkException("Error in checking cURL version for TLS 1.2. Error Num:[" . curl_errno($curl) . "] Error message:[" . curl_error($curl) . "]");
}else{
$tlsVersion = json_decode($curlVersionResponse)->tls_version;
}
curl_close($curl);
return $tlsVersion;
} | php | {
"resource": ""
} |
q255715 | IdsExceptionManager.HandleException | test | public static function HandleException($errorMessage=null, $errorCode=null, $source=null, $innerException=null)
{
$message = implode(", ", array($errorMessage, $errorCode, $source));
throw new IdsException($message);
} | php | {
"resource": ""
} |
q255716 | MetadataExtractor.verifyVariableType | test | private function verifyVariableType($value)
{
// if value can be mapped to simple type
if (in_array(strtolower($value), array("string","float","double","boolean", "integer"))) {
return new SimpleEntity(strtolower($value));
}
// generate names
// try it
foreach ($this->generateObjectNames($value) as $name) {
$name = $this->addNameSpaceToPotentialClassName($name);
if (class_exists($name)) {
return new ObjectEntity($name);
}
}
return new UnknownEntity($value);
} | php | {
"resource": ""
} |
q255717 | MetadataExtractor.generateObjectNames | test | private function generateObjectNames($value)
{
$reversiveStack = array();
$reversiveStack[] = $value; // add original value. It will be called last
$reversiveStack[] = $this->removeArrayBrackets($value); //
$reversiveStack[] = $this->getIntuitName($this->removeArrayBrackets($value));
$reversiveStack[] = $this->getIntuitName($this->removeArrayBrackets($this->getClassNameFromPackagePath($value)));
$reversiveStack[] = $this->removeArrayBrackets($this->getClassNameFromPackagePath($value));
$reversiveStack[] = $this->getClassNameFromPackagePath($value);
return array_reverse($reversiveStack);
} | php | {
"resource": ""
} |
q255718 | MetadataExtractor.completeProperty | test | private function completeProperty($a, ReflectionProperty $p)
{
if (!$a instanceof AbstractEntity) {
throw new InvalidArgumentException("Expected instance of AbstractEntity here");
}
$a->setName($p->getName());
$a->setClass($p->getDeclaringClass());
} | php | {
"resource": ""
} |
q255719 | Bind.unmarshal | test | public function unmarshal($xml)
{
// Get all namespaces
$this->dom = new \DOMDocument();
if ($this->debug) {
$this->dom->formatOutput = true;
}
$this->dom->loadXML($xml);
$this->namespaces = $this->getDocNamespaces($this->dom);
// Find targetNamespace
$xpath = new \DOMXPath($this->dom);
$query = ".";
$root = $xpath->query($query);
$ns = $code = "";
foreach ($root as $rt) {
list($ns, $name) = $this->parseQName($rt->nodeName, true);
}
$className = $this->urnToPhpName($ns)."\\".$this->classPrefix.$name;
if (!class_exists($className, CoreConstants::USE_AUTOLOADER)) {
throw new \RuntimeException('Class '.$className. ' is not found. Make sure it was included');
}
$binding = new $className();
return $this->bindXml($xml, $binding);
// Instantiate class
// Assign corresponding nodes to properties/classes
// return PHP binding
} | php | {
"resource": ""
} |
q255720 | CoreHelper.GetSerializer | test | public static function GetSerializer($serviceContext, $isRequest)
{
$serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "GetSerializer");
$serializer = null;
if ($isRequest) {
switch ($serviceContext->IppConfiguration->Message->Request->SerializationFormat) {
case SerializationFormat::Xml:
$serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "GetSerializer(Request): Xml");
$serializer = new XmlObjectSerializer();
break;
case SerializationFormat::Json:
$serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "GetSerializer(Request): JSON");
$serializer = new JsonObjectSerializer();
break;
case SerializationFormat::Custom:
// TODO: check whtether this is possible
// $this->serializer = $serviceContext->IppConfiguration->Message->Request->CustomSerializer;
$serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "GetSerializer(Request): Custom");
break;
}
} else {
switch ($serviceContext->IppConfiguration->Message->Response->SerializationFormat) {
case SerializationFormat::Xml:
$serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "GetSerializer(Response): XML");
$serializer = new XmlObjectSerializer();
break;
case SerializationFormat::Json:
$serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "GetSerializer(Response): JSON");
$serializer = new JsonObjectSerializer();
break;
case SerializationFormat::Custom:
// TODO: check whtether this is possible
// $this->serializer = $serviceContext->IppConfiguration->Message->Response->CustomSerializer;
$serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "GetSerializer(Response): Custom");
break;
}
}
return $serializer;
} | php | {
"resource": ""
} |
q255721 | CoreHelper.GetCompressor | test | public static function GetCompressor($serviceContext, $isRequest)
{
$compressor = null;
if ($isRequest) {
switch ($serviceContext->IppConfiguration->Message->Request->CompressionFormat) {
case CompressionFormat::GZip:
$compressor = new GZipCompressor();
break;
case CompressionFormat::Deflate:
$compressor = new DeflateCompressor();
break;
}
} else {
switch ($serviceContext->IppConfiguration->Message->Response->CompressionFormat) {
case CompressionFormat::GZip:
$compressor = new GZipCompressor();
break;
case CompressionFormat::Deflate:
$compressor = new DeflateCompressor();
break;
}
}
return $compressor;
} | php | {
"resource": ""
} |
q255722 | CoreHelper.GetRequestLogging | test | public static function GetRequestLogging($serviceContext)
{
$requestLogger = null;
try {
if (isset($serviceContext->IppConfiguration) &&
isset($serviceContext->IppConfiguration->Logger) &&
isset($serviceContext->IppConfiguration->Logger->RequestLog) &&
isset($serviceContext->IppConfiguration->Logger->RequestLog->EnableRequestResponseLogging) &&
isset($serviceContext->IppConfiguration->Logger->RequestLog->ServiceRequestLoggingLocation)) {
$requestLogger = new LogRequestsToDisk(
$serviceContext->IppConfiguration->Logger->RequestLog->EnableRequestResponseLogging,
$serviceContext->IppConfiguration->Logger->RequestLog->ServiceRequestLoggingLocation);
} else {
$requestLogger = new LogRequestsToDisk(false, null);
}
} catch (\Exception $e) {
$requestLogger = new LogRequestsToDisk(false, null);
}
return $requestLogger;
} | php | {
"resource": ""
} |
q255723 | Zend_Soap_Wsdl_Strategy_Composite.connectTypeToStrategy | test | public function connectTypeToStrategy($type, $strategy)
{
if (!is_string($type)) {
/**
* @see Zend_Soap_Wsdl_Exception
*/
require_once "Zend/Soap/Wsdl/Exception.php";
throw new Zend_Soap_Wsdl_Exception("Invalid type given to Composite Type Map.");
}
$this->_typeMap[$type] = $strategy;
return $this;
} | php | {
"resource": ""
} |
q255724 | Zend_Soap_Wsdl_Strategy_Composite.getDefaultStrategy | test | public function getDefaultStrategy()
{
$strategy = $this->_defaultStrategy;
if (is_string($strategy) && class_exists($strategy)) {
$strategy = new $strategy;
}
if (!($strategy instanceof Zend_Soap_Wsdl_Strategy_Interface)) {
/**
* @see Zend_Soap_Wsdl_Exception
*/
require_once "Zend/Soap/Wsdl/Exception.php";
throw new Zend_Soap_Wsdl_Exception(
"Default Strategy for Complex Types is not a valid strategy object."
);
}
$this->_defaultStrategy = $strategy;
return $strategy;
} | php | {
"resource": ""
} |
q255725 | Zend_Soap_Wsdl_Strategy_Composite.getStrategyOfType | test | public function getStrategyOfType($type)
{
if (isset($this->_typeMap[$type])) {
$strategy = $this->_typeMap[$type];
if (is_string($strategy) && class_exists($strategy)) {
$strategy = new $strategy();
}
if (!($strategy instanceof Zend_Soap_Wsdl_Strategy_Interface)) {
/**
* @see Zend_Soap_Wsdl_Exception
*/
require_once "Zend/Soap/Wsdl/Exception.php";
throw new Zend_Soap_Wsdl_Exception(
"Strategy for Complex Type '".$type."' is not a valid strategy object."
);
}
$this->_typeMap[$type] = $strategy;
} else {
$strategy = $this->getDefaultStrategy();
}
return $strategy;
} | php | {
"resource": ""
} |
q255726 | Zend_Soap_Wsdl_Strategy_Composite.addComplexType | test | public function addComplexType($type)
{
if (!($this->_context instanceof Zend_Soap_Wsdl)) {
/**
* @see Zend_Soap_Wsdl_Exception
*/
require_once "Zend/Soap/Wsdl/Exception.php";
throw new Zend_Soap_Wsdl_Exception(
"Cannot add complex type '".$type."', no context is set for this composite strategy."
);
}
$strategy = $this->getStrategyOfType($type);
$strategy->setContext($this->_context);
return $strategy->addComplexType($type);
} | php | {
"resource": ""
} |
q255727 | DomainEntityBuilder.makeReflection | test | private function makeReflection()
{
if (!class_exists($this->getOriginalClassName())) {
throw new InvalidArgumentException('Class name ' . $this->getOriginalClassName() . ' not exists');
}
$this->reflection = new ReflectionClass($this->getOriginalClassName());
} | php | {
"resource": ""
} |
q255728 | DomainEntityBuilder.populatePropertyComments | test | private function populatePropertyComments()
{
if (is_null($this->properties)) {
throw new UnexpectedValueException('Properties are expected here');
}
if (!is_array($this->properties)) {
throw new UnexpectedValueException('Properties should be provided as array');
}
// if nothing to do here
if (is_array($this->properties) && empty($this->properties)) {
return null;
}
$extractor = new MetadataExtractor();
$this->model = $extractor->processComments($this->properties);
} | php | {
"resource": ""
} |
q255729 | DomainEntityBuilder.forgeInstance | test | private function forgeInstance($instance)
{
$reflection = new ReflectionClass($instance);
foreach ($reflection->getProperties() as $key => $property) {
if (!$property instanceof ReflectionProperty) {
continue;
}
$entity = $this->getEntityFromModel($key, $property->getName());
$value = $property->getValue($instance);
if (is_array($value)) {
$this->processPropertyValues($instance, $property, $entity, $value);
} else {
$this->processPropertyValue($instance, $property, $entity, $value);
}
}
return $instance;
} | php | {
"resource": ""
} |
q255730 | DomainEntityBuilder.processPropertyValues | test | private function processPropertyValues($instance, $property, $model, $values)
{
$changed = false;
foreach ($values as &$value) {
if (!$this->isMorhing($model, $value)) {
continue;
}
$newType = $model->getType();
//$value = new $newType( (array) $value );
$value = static::create($newType, (array) $value);
$changed = true;
}
if ($changed) {
$property->setValue($instance, $values);
}
} | php | {
"resource": ""
} |
q255731 | DomainEntityBuilder.create | test | public static function create($type, $values)
{
$i = new static($type);
$i->usePropertyValues($values);
return $i->createInstance();
} | php | {
"resource": ""
} |
q255732 | DomainEntityBuilder.isMorhing | test | private function isMorhing($entity, $value)
{
if (!$entity instanceof ObjectEntity) {
return false;
}
//String, numeric are fine
if (!is_object($value)) {
return false;
}
// if object has same type already (it's wierd, but ok)
if (get_class($value) === $entity->getType()) {
return false;
}
// we expect stdClass here only
if (!$value instanceof \stdClass) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q255733 | DomainEntityBuilder.processPropertyValue | test | private function processPropertyValue($instance, $property, $model, $value)
{
if ($this->isMorhing($model, $value)) {
$newType = $model->getType();
$new = static::create($newType, (array) $value);
$property->setValue($instance, $new);
}
} | php | {
"resource": ""
} |
q255734 | DomainEntityBuilder.getEntityFromModel | test | private function getEntityFromModel($index, $propertyName)
{
$entity = $this->model[$index];
if ($entity->getName() === $propertyName) {
return $entity;
}
// TODO Do we need to implement search by name in model?
throw new RuntimeException("Unexpected $propertyName by the given index.");
} | php | {
"resource": ""
} |
q255735 | DataService.updateServiceContextSettingsForOthers | test | public function updateServiceContextSettingsForOthers($serviceContext)
{
$this->setupServiceContext($serviceContext);
$this->setupSerializers();
$this->useMinorVersion();
$this->setupRestHandler($serviceContext);
} | php | {
"resource": ""
} |
q255736 | DataService.setupRestHandler | test | protected function setupRestHandler($serviceContext)
{
if(isset($serviceContext)){
$client = ClientFactory::createClient($this->getClientName());
$this->restHandler = new SyncRestHandler($serviceContext, $client);
}else{
throw new SdkException("Can not set the Rest Client based on null ServiceContext.");
}
return $this;
} | php | {
"resource": ""
} |
q255737 | DataService.setLogLocation | test | public function setLogLocation($new_log_location)
{
$restHandler = $this->restHandler;
$loggerUsedByRestHandler = $restHandler->getRequestLogger();
$loggerUsedByRestHandler->setLogDirectory($new_log_location);
return $this;
} | php | {
"resource": ""
} |
q255738 | DataService.setMinorVersion | test | public function setMinorVersion($newMinorVersion)
{
$serviceContext = $this->getServiceContext();
$serviceContext->setMinorVersion($newMinorVersion);
$this->updateServiceContextSettingsForOthers($serviceContext);
return $this;
} | php | {
"resource": ""
} |
q255739 | DataService.disableLog | test | public function disableLog()
{
$restHandler = $this->restHandler;
$loggerUsedByRestHandler = $restHandler->getRequestLogger();
$loggerUsedByRestHandler->setLogStatus(false);
return $this;
} | php | {
"resource": ""
} |
q255740 | DataService.enableLog | test | public function enableLog()
{
$restHandler = $this->restHandler;
$loggerUsedByRestHandler = $restHandler->getRequestLogger();
$loggerUsedByRestHandler->setLogStatus(true);
return $this;
} | php | {
"resource": ""
} |
q255741 | DataService.setClientName | test | public function setClientName($clientName){
$this->clientName = $clientName;
$serviceContext = $this->getServiceContext();
$this->setupRestHandler($serviceContext);
return $this;
} | php | {
"resource": ""
} |
q255742 | DataService.Configure | test | public static function Configure($settings)
{
if (isset($settings)) {
if (is_array($settings)) {
$ServiceContext = ServiceContext::ConfigureFromPassedArray($settings);
if (!isset($ServiceContext)) {
throw new SdkException('Construct ServiceContext from OAuthSettigs failed.');
}
$DataServiceInstance = new DataService($ServiceContext);
} elseif (is_string($settings)) {
$ServiceContext = ServiceContext::ConfigureFromLocalFile($settings);
if (!isset($ServiceContext)) {
throw new SdkException('Construct ServiceContext from File failed.');
}
$DataServiceInstance = new DataService($ServiceContext);
}
if($ServiceContext->IppConfiguration->OAuthMode == CoreConstants::OAUTH2)
{
$oauth2Config = $ServiceContext->IppConfiguration->Security;
if($oauth2Config instanceof OAuth2AccessToken){
$DataServiceInstance->configureOAuth2LoginHelper($oauth2Config, $settings);
}else{
throw new SdkException("SDK Error. OAuth mode is not OAuth 2.");
}
}
return $DataServiceInstance;
} else {
throw new SdkException("Passed Null to Configure method. It expects either a file path for the config file or an array containing OAuth settings and BaseURL.");
}
} | php | {
"resource": ""
} |
q255743 | DataService.configureOAuth2LoginHelper | test | private function configureOAuth2LoginHelper($oauth2Conifg, $settings)
{
$refreshToken = CoreConstants::getRefreshTokenFromArray($settings);
if(isset($refreshToken)){
//Login helper for refresh token API call
$this->OAuth2LoginHelper = new OAuth2LoginHelper(null,
null,
null,
null,
null,
$this->getServiceContext());
}else{
$redirectURL = CoreConstants::getRedirectURL($settings);
$scope = array_key_exists('scope', $settings) ? $settings['scope'] : null;
$state = array_key_exists('state', $settings) ? $settings['state'] : null;
$this->OAuth2LoginHelper = new OAuth2LoginHelper($oauth2Conifg->getClientID(),
$oauth2Conifg->getClientSecret(),
$redirectURL,
$scope,
$state);
}
} | php | {
"resource": ""
} |
q255744 | DataService.updateOAuth2Token | test | public function updateOAuth2Token($newOAuth2AccessToken)
{
try{
$this->serviceContext->updateOAuth2Token($newOAuth2AccessToken);
$realmID = $newOAuth2AccessToken->getRealmID();
$this->serviceContext->realmId = $realmID;
$this->setupRestHandler($this->serviceContext);
} catch (SdkException $e){
$this->serviceContext->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Error, "Encountered an error while updating OAuth2Token." . $e->getMessage());
$this->serviceContext->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Error, "Stack Trace: " . $e->getTraceAsString());
}
return $this;
} | php | {
"resource": ""
} |
q255745 | DataService.setupSerializers | test | public function setupSerializers()
{
$this->responseSerializer = CoreHelper::GetSerializer($this->serviceContext, false);
$this->requestSerializer = CoreHelper::GetSerializer($this->serviceContext, true);
} | php | {
"resource": ""
} |
q255746 | DataService.Update | test | public function Update($entity)
{
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called Method: Update.");
// Validate parameter
if (!$entity) {
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Error, "Argument Null Exception");
throw new IdsException('Argument Null Exception');
}
$this->verifyOperationAccess($entity, __FUNCTION__);
$httpsPostBody = $this->executeObjectSerializer($entity, $urlResource);
// Builds resource Uri
// Handle some special cases
if ((strtolower('preferences') == strtolower($urlResource)) &&
(CoreConstants::IntuitServicesTypeQBO == $this->serviceContext->serviceType)
) {
// URL format for *QBO* prefs request is different than URL format for *QBD* prefs request
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource));
}
//We no longer support QBD on PHP SDK The code is removed.
/*else if ((strtolower('company') == strtolower($urlResource)) &&
(CoreConstants::IntuitServicesTypeQBO == $this->serviceContext->serviceType)) {
// URL format for *QBD* companyinfo request is different than URL format for *QBO* companyinfo request
$urlResource = 'companyInfo';
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource . '?operation=update'));
}*/ else {
// Normal case
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource . '?operation=update'));
}
// Send Request and return response
return $this->sendRequestParseResponseBodyAndHandleHttpError($entity, $uri, $httpsPostBody, DataService::UPDATE);
} | php | {
"resource": ""
} |
q255747 | DataService.Add | test | public function Add($entity)
{
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called Method Add.");
// Validate parameter
if (!$entity) {
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Error, "Argument Null Exception");
throw new IdsException('Argument Null Exception');
}
$this->verifyOperationAccess($entity, __FUNCTION__);
if ($this->isJsonOnly($entity)) {
$this->forceJsonSerializers();
}
$httpsPostBody = $this->executeObjectSerializer($entity, $urlResource);
// Builds resource Uri
$resourceURI = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource));
$uri = $this->handleTaxService($entity, $resourceURI);
// Send request
return $this->sendRequestParseResponseBodyAndHandleHttpError($entity, $uri, $httpsPostBody, DataService::ADD);
} | php | {
"resource": ""
} |
q255748 | DataService.Delete | test | public function Delete($entity)
{
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called Method Delete.");
// Validate parameter
if (!$entity) {
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Error, "Argument Null Exception");
throw new IdsException('Argument Null Exception');
}
$this->verifyOperationAccess($entity, __FUNCTION__);
// Builds resource Uri
$httpsPostBody = $this->executeObjectSerializer($entity, $urlResource);
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource . '?operation=delete'));
// Creates request
return $this->sendRequestParseResponseBodyAndHandleHttpError($entity, $uri, $httpsPostBody, DataService::DELETE);
} | php | {
"resource": ""
} |
q255749 | DataService.Upload | test | public function Upload($imgBits, $fileName, $mimeType, $objAttachable)
{
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called Method Upload.");
// Validate parameter
if (!$imgBits || !$mimeType || !$fileName) {
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Error, "Argument Null Exception");
throw new IdsException('Argument Null Exception');
}
// Builds resource Uri
$urlResource = "upload";
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, $urlResource));
$boundaryString = md5(time());
$MetaData = $this->executeObjectSerializer($objAttachable, $urlResource);
$desiredIdentifier = '0';
$newline = "\r\n";
$dataMultipart = '';
$dataMultipart .= '--' . $boundaryString . $newline;
$dataMultipart .= "Content-Disposition: form-data; name=\"file_metadata_{$desiredIdentifier}\"" . $newline;
$dataMultipart .= "Content-Type: " . CoreConstants::CONTENTTYPE_APPLICATIONXML . '; charset=UTF-8' . $newline;
$dataMultipart .= 'Content-Transfer-Encoding: 8bit' . $newline . $newline;
$dataMultipart .= $MetaData;
$dataMultipart .= '--' . $boundaryString . $newline;
$dataMultipart .= "Content-Disposition: form-data; name=\"file_content_{$desiredIdentifier}\"; filename=\"{$fileName}\"" . $newline;
$dataMultipart .= "Content-Type: {$mimeType}" . $newline;
$dataMultipart .= 'Content-Transfer-Encoding: base64' . $newline . $newline;
$dataMultipart .= chunk_split(base64_encode($imgBits)) . $newline;
$dataMultipart .= "--" . $boundaryString . "--" . $newline . $newline; // finish with two eol's!!
return $this->sendRequestParseResponseBodyAndHandleHttpError(null, $uri, $dataMultipart, DataService::UPLOAD, $boundaryString);
} | php | {
"resource": ""
} |
q255750 | DataService.SendEmail | test | public function SendEmail($entity, $email = null)
{
$this->validateEntityId($entity);
$this->verifyOperationAccess($entity, __FUNCTION__);
$entityId=$this->getIDString($entity->Id);
$uri = implode(CoreConstants::SLASH_CHAR, array('company',
$this->serviceContext->realmId,
self::getEntityResourceName($entity),
$entityId,
'send'));
if (is_null($email)) {
$this->logInfo("Entity " . get_class($entity) . " with id=" . $entityId . " is using default email");
} else {
$this->logInfo("Entity " . get_class($entity) . " with id=" . $entityId . " is using $email");
if (!$this->verifyEmailAddress($email)) {
$this->logError("Valid email is expected, but received $email");
throw new SdkException("Valid email is expected, but received $email");
}
}
return $this->sendRequestParseResponseBodyAndHandleHttpError($entity, $uri, null, DataService::SENDEMAIL, null, $email);
} | php | {
"resource": ""
} |
q255751 | DataService.Query | test | public function Query($query, $startPosition = null, $maxResults = null)
{
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called Method Query.");
if ('QBO' == $this->serviceContext->serviceType) {
$httpsContentType = CoreConstants::CONTENTTYPE_APPLICATIONTEXT;
} else {
$httpsContentType = CoreConstants::CONTENTTYPE_TEXTPLAIN;
}
$httpsUri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, 'query'));
$httpsPostBody = $this->appendPaginationInfo($query, $startPosition, $maxResults);
$requestParameters = $this->getPostRequestParameters($httpsUri, $httpsContentType);
$restRequestHandler = $this->getRestHandler();
list($responseCode, $responseBody) = $restRequestHandler->sendRequest($requestParameters, $httpsPostBody, null, $this->isThrownExceptionOnError());
$faultHandler = $restRequestHandler->getFaultHandler();
if ($faultHandler) {
$this->lastError = $faultHandler;
return null;
} else {
$this->lastError = false;
$parsedResponseBody = null;
try {
$responseXmlObj = simplexml_load_string($responseBody);
if ($responseXmlObj && $responseXmlObj->QueryResponse) {
$tmpXML = $responseXmlObj->QueryResponse->asXML();
}
$parsedResponseBody = $this->responseSerializer->Deserialize($tmpXML, false);
$this->serviceContext->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Info, $parsedResponseBody);
} catch (\Exception $e) {
throw new \Exception("Exception appears in converting Response to XML.");
}
return $parsedResponseBody;
}
} | php | {
"resource": ""
} |
q255752 | DataService.appendPaginationInfo | test | private function appendPaginationInfo($query, $startPosition, $maxResults){
$query = trim($query);
if(isset($startPosition) && !empty($startPosition)){
if(stripos($query, "STARTPOSITION") === false){
if(stripos($query, "MAXRESULTS") !== false){
//In MaxResult is defined,we don't set startPosition
}else{
$query = $query . " " . "STARTPOSITION " . $startPosition;
}
}else{
//Ignore the startPosition if it is already used on the query
}
}
if(isset($maxResults) && !empty($maxResults)){
if(stripos($query, "MAXRESULTS") === false){
$query = $query . " " . "MAXRESULTS " . $maxResults;
}else{
//Ignore the maxResults if it is already used on the query
}
}
return $query;
} | php | {
"resource": ""
} |
q255753 | DataService.FindAll | test | public function FindAll($entityName, $pageNumber = 0, $pageSize = 500)
{
$this->serviceContext->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called Method FindAll.");
$phpClassName = DataService::decorateIntuitEntityToPhpClassName($entityName);
// Handle some special cases
if (strtolower('company') == strtolower($entityName)) {
$entityName = 'CompanyInfo';
}
if ('QBO' == $this->serviceContext->serviceType) {
$httpsContentType = CoreConstants::CONTENTTYPE_APPLICATIONTEXT;
} else {
$httpsContentType = CoreConstants::CONTENTTYPE_TEXTPLAIN;
}
$httpsUri = implode(CoreConstants::SLASH_CHAR, array('company', $this->serviceContext->realmId, 'query'));
$httpsPostBody = "select * from $entityName startPosition $pageNumber maxResults $pageSize";
$requestParameters = $this->getPostRequestParameters($httpsUri, $httpsContentType);
$restRequestHandler = $this->getRestHandler();
list($responseCode, $responseBody) = $restRequestHandler->sendRequest($requestParameters, $httpsPostBody, null, $this->isThrownExceptionOnError());
$faultHandler = $restRequestHandler->getFaultHandler();
if ($faultHandler) {
$this->lastError = $faultHandler;
return null;
} else {
$this->lastError = false;
$parsedResponseBody = null;
try {
$responseXmlObj = simplexml_load_string($responseBody);
if ($responseXmlObj && $responseXmlObj->QueryResponse) {
$parsedResponseBody = $this->responseSerializer->Deserialize($responseXmlObj->QueryResponse->asXML(), false);
}
} catch (\Exception $e) {
throw new \Exception("Exception appears in converting Response to XML.");
}
return $parsedResponseBody;
}
} | php | {
"resource": ""
} |
q255754 | DataService.CDC | test | public function CDC($entityList, $changedSince)
{
$this->serviceContext->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Info, "Called Method CDC.");
// Validate parameter
if (count($entityList) <= 0) {
$exception = new IdsException('ParameterNotNullMessage');
$this->serviceContext->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Error, "ParameterNotNullMessage");
IdsExceptionManager::HandleException($exception);
}
$entityString = implode(",", $entityList);
$query = null;
$uri = null;
if(is_string($changedSince)){
$formattedChangedSince = trim($changedSince);
}else{
$formattedChangedSince = date("Y-m-d\TH:i:s", $this->verifyChangedSince($changedSince));
}
$query = "entities=" . $entityString . "&changedSince=" . $formattedChangedSince;
$uri = "company/{1}/cdc?{2}";
//$uri = str_replace("{0}", CoreConstants::VERSION, $uri);
$uri = str_replace("{1}", $this->serviceContext->realmId, $uri);
$uri = str_replace("{2}", $query, $uri);
// Creates request parameters
$requestParameters = $this->getGetRequestParameters($uri, CoreConstants::CONTENTTYPE_APPLICATIONXML);
$restRequestHandler = $this->getRestHandler();
list($responseCode, $responseBody) = $restRequestHandler->sendRequest($requestParameters, null, null, $this->isThrownExceptionOnError());
$faultHandler = $restRequestHandler->getFaultHandler();
if ($faultHandler) {
$this->lastError = $faultHandler;
return null;
} else {
$this->lastError = false;
$returnValue = new IntuitCDCResponse();
try {
$xmlObj = simplexml_load_string($responseBody);
$responseArray = $xmlObj->CDCResponse->QueryResponse;
if(sizeof($responseArray) != sizeof($entityList)){
throw new ServiceException("The number of Entities requested on CDC does not match the number of Response.");
}
for($i = 0; $i < sizeof($responseArray); $i++){
$currentResponse = $responseArray[$i];
$currentEntityName = $entityList[$i];
$entities = $this->responseSerializer->Deserialize($currentResponse->asXML(), false);
$entityName = $currentEntityName;
//If we find the actual name, update it.
foreach ($currentResponse->children() as $currentResponseChild) {
$entityName = (string)$currentResponseChild->getName();
break;
}
$returnValue->entities[$entityName] = $entities;
}
} catch (\Exception $e) {
IdsExceptionManager::HandleException($e);
}
$this->serviceContext->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Info, "Finished Executing Method CDC.");
return $returnValue;
}
} | php | {
"resource": ""
} |
q255755 | DataService.executeObjectSerializer | test | protected function executeObjectSerializer($entity, &$urlResource)
{
//
$result = $this->getRequestSerializer()->Serialize($entity);
$urlResource = $this->getRequestSerializer()->getResourceURL();
return $result;
} | php | {
"resource": ""
} |
q255756 | DataService.initPostRequest | test | protected function initPostRequest($entity, $uri)
{
return $this->isJsonOnly($entity)
? $this->getPostJsonRequest($uri)
: $this->getPostRequest($uri);
} | php | {
"resource": ""
} |
q255757 | DataService.getRequestParameters | test | protected function getRequestParameters($uri, $method, $type, $apiName = null)
{
return new RequestParameters($uri, $method, $type, $apiName);
} | php | {
"resource": ""
} |
q255758 | DataService.fixTaxServicePayload | test | private function fixTaxServicePayload($entity, $content)
{
if ($this->isTaxServiceSafe($entity)) {
//get first "line" to make sure we don't have TaxService in response
$sample = substr(trim($content), 0, 20);
$taxServiceName = self::cleanPhpClassNameToIntuitEntityName(get_class($entity));
if (false === strpos($sample, $taxServiceName)) {
//last attempt to verify content before
if (0 === strpos($sample, '{"TaxCode":')) {
return "{\"$taxServiceName\":$content}";
}
}
}
return $content;
} | php | {
"resource": ""
} |
q255759 | DataService.getExportFileNameForPDF | test | public function getExportFileNameForPDF($entity, $ext, $usetimestamp = true)
{
//TODO: add timestamp or GUID
$this->validateEntityId($entity);
return self::getEntityResourceName($entity) . "_" . $this->getIDString($entity->Id) . ($usetimestamp ? "_" . time() : "") . ".$ext";
} | php | {
"resource": ""
} |
q255760 | DataService.isAllowed | test | private function isAllowed($entity, $method)
{
$className = get_class($entity);
if (!$className) {
$this->logError("Intuit entity is expected here instead of $entity");
throw new IdsException('Unexpected Argument Exception');
}
$classArray = explode('\\', $className);
$trimedClassName = end($classArray);
return $this->serviceContext->IppConfiguration->OpControlList->isAllowed($trimedClassName, $method);
} | php | {
"resource": ""
} |
q255761 | DataService.CreateNewBatch | test | public function CreateNewBatch()
{
$batch = new Batch($this->serviceContext, $this->getRestHandler(), $this->isThrownExceptionOnError());
return $batch;
} | php | {
"resource": ""
} |
q255762 | DataService.convertToTimestamp | test | private function convertToTimestamp($str)
{
$result = date_parse($str);
if (!$result) {
return false;
}
if (empty($result) || !is_array($result)) {
return false;
}
extract($result);
if (!empty($errors)) {
throw new SdkException("SDK failed to parse date value \"$str\":"
. (is_array($errors) ? implode("\n", $errors) : $errors)
);
}
//@TODO: mktime is deprecated since 5.3.0, this package needs 5.6
return mktime($hour, $minute, $second, $month, $day, $year);
} | php | {
"resource": ""
} |
q255763 | DataService.isValidTimeStamp | test | public function isValidTimeStamp($timestamp)
{
return ((string)(int)$timestamp === $timestamp) && ($timestamp <= PHP_INT_MAX) && ($timestamp >= ~PHP_INT_MAX);
} | php | {
"resource": ""
} |
q255764 | DataService.verifyChangedSince | test | protected function verifyChangedSince($value)
{
if (is_int($value)) {
return $value;
}
// remove whitespaces, tabulation etc
$trimmed = trim($value);
if ($this->isValidTimeStamp($trimmed)) {
return $trimmed;
}
//at this point we have numeric string which is not timestamp
if (is_numeric($value)) {
throw new SdkException("Input string doesn't look as unix timestamp or date string");
}
// trying to parse string into timestamp
$converted = $this->convertToTimestamp($value);
if (!$converted) {
throw new SdkException("Input value should be unix timestamp or valid date string");
}
return $converted;
} | php | {
"resource": ""
} |
q255765 | DataService.getCompanyInfo | test | public function getCompanyInfo()
{
$currentServiceContext = $this->getServiceContext();
if (!isset($currentServiceContext) || empty($currentServiceContext->realmId)) {
throw new SdkException("Please Setup Service Context before making get CompanyInfo call.");
}
//The CompanyInfo URL
$uri = implode(CoreConstants::SLASH_CHAR, array('company', $currentServiceContext->realmId, 'companyinfo', $currentServiceContext->realmId));
$requestParameters = new RequestParameters($uri, 'GET', CoreConstants::CONTENTTYPE_APPLICATIONXML, null);
$restRequestHandler = $this->getRestHandler();
list($responseCode, $responseBody) = $restRequestHandler->sendRequest($requestParameters, null, null, $this->isThrownExceptionOnError());
$faultHandler = $restRequestHandler->getFaultHandler();
//$faultHandler now is true or false
if ($faultHandler) {
$this->lastError = $faultHandler;
return null;
} else {
$this->lastError = false;
$parsedResponseBody = $this->getResponseSerializer()->Deserialize($responseBody, true);
return $parsedResponseBody;
}
} | php | {
"resource": ""
} |
q255766 | CoreConstants.getQuickBooksOnlineAPIEntityRules | test | public static function getQuickBooksOnlineAPIEntityRules()
{
return
array(
'*' => array(
"DownloadPDF" => false,
"jsonOnly" => false,
"SendEmail"=> false),
"IPPTaxService" => array( '*' => false,
'Add' => true,
'jsonOnly' => true),
"IPPSalesReceipt" => array( "DownloadPDF" => true, "SendEmail" => true ),
"IPPInvoice" => array( "DownloadPDF" => true, "SendEmail" => true ),
"IPPEstimate" => array( "DownloadPDF" => true, "SendEmail" => true ),
);
} | php | {
"resource": ""
} |
q255767 | CoreConstants.getAccessTokenFromArray | test | public static function getAccessTokenFromArray(array $settings){
if(array_key_exists('accessTokenKey', $settings)){
return $settings['accessTokenKey'];
}else if(array_key_exists('accessToken', $settings)){
return $settings['accessToken'];
} else if(array_key_exists('AccessToken', $settings)){
return $settings['AccessToken'];
} else{
return null;
}
} | php | {
"resource": ""
} |
q255768 | CoreConstants.getRefreshTokenFromArray | test | public static function getRefreshTokenFromArray(array $settings){
if(array_key_exists('refreshTokenKey', $settings)){
return $settings['refreshTokenKey'];
}else if(array_key_exists('refreshToken', $settings)){
return $settings['refreshToken'];
} else if(array_key_exists('RefreshToken', $settings)){
return $settings['RefreshToken'];
} else{
return null;
}
} | php | {
"resource": ""
} |
q255769 | CoreConstants.getRedirectURL | test | public static function getRedirectURL(array $settings){
if(array_key_exists('redirectURL', $settings)){
return $settings['redirectURL'];
}else if(array_key_exists('RedirectUrl', $settings)){
return $settings['RedirectUrl'];
} else if(array_key_exists('redirecturl', $settings)){
return $settings['redirecturl'];
} else if(array_key_exists('redirectUrl', $settings)){
return $settings['redirectUrl'];
} else if(array_key_exists('RedirectURL', $settings)){
return $settings['RedirectURL'];
} else if(array_key_exists('redirectURI', $settings)){
return $settings['redirectURI'];
}else if(array_key_exists('RedirectUri', $settings)){
return $settings['RedirectUri'];
} else if(array_key_exists('redirecturi', $settings)){
return $settings['redirecturl'];
} else if(array_key_exists('redirectUri', $settings)){
return $settings['redirectUrl'];
} else if(array_key_exists('RedirectURI', $settings)){
return $settings['RedirectURI'];
}
else{
return null;
}
} | php | {
"resource": ""
} |
q255770 | ContentWriter.saveFile | test | public function saveFile($dir, $name=null)
{
if (empty($dir)) {
throw new SdkException("Directory is empty.");
}
if (!file_exists($dir)) {
throw new SdkException("Directory ($dir) doesn't exist.");
}
if (!is_writable($dir)) {
throw new SdkException("Directory ($dir) is not writable");
}
$this->tempPath = $dir . DIRECTORY_SEPARATOR . $this->generateFileName($name);
if (file_exists($this->tempPath)) {
throw new SdkException("File ($this->tempPath) already exists");
}
try {
$result = file_put_contents($this->tempPath, $this->getContent());
} catch (\Exception $e) {
if (!is_writable($this->tempPath)) {
throw new SdkException("File ({$this->tempPath}) is not writable");
}
throw new SdkException("Error was thrown: " . $e->getMessage() . "\File: " .$e->getFile() ." on line " . $e->getLine());
}
if (false === $result) {
throw new SdkException('Unable to write content into temp file: ' . $this->tempPath);
}
$this->bytes = $result;
} | php | {
"resource": ""
} |
q255771 | ContentWriter.generateFileName | test | private function generateFileName($name)
{
$filename = is_null($name) ? $this->getUniqId() : $name;
return is_null($this->getPrefix()) ? $filename : $this->getPrefix() . $filename;
} | php | {
"resource": ""
} |
q255772 | FaultHandler.generateErrorFromOAuthMsg | test | private function generateErrorFromOAuthMsg($OAuthException)
{
if (get_class($OAuthException) == 'OAuthException') {
$this->httpStatusCode = $OAuthException->getCode();
$this->helpMsg = $OAuthException->getMessage();
$this->responseBody = $OAuthException->lastResponse;
} else {
throw new \Exception("OAuthException required for generate error from Intuit. The passed parameters for Fault handler is not OAuthException");
}
} | php | {
"resource": ""
} |
q255773 | FaultHandler.parseResponse | test | public function parseResponse($message){
$xmlObj = simplexml_load_string($message);
if(!$this->isTheErrorBodyInStandardFormat($xmlObj)){
return;
}
$type = (string)$xmlObj->Fault->attributes()['type'];
if(isset($type) && !empty($type)){
$this->intuitErrorType = $type;
}
$code = (string)$xmlObj->Fault->Error->attributes()['code'];
if(isset($code) && !empty($code)){
$this->intuitErrorCode = $code;
}
$element = (string)$xmlObj->Fault->Error->attributes()['element'];
if(isset($element) && !empty($element)){
$this->intuitErrorElement = $element;
}
$message = (string)$xmlObj->Fault->Error->Message;
if(isset($message) && !empty($message)){
$this->intuitErrorMessage = $message;
}
$detail = (string)$xmlObj->Fault->Error->Detail;
if(isset($detail) && !empty($detail)){
$this->intuitErrorDetail = $detail;
}
} | php | {
"resource": ""
} |
q255774 | FaultHandler.isTheErrorBodyInStandardFormat | test | private function isTheErrorBodyInStandardFormat($xmlObj)
{
if(!isset($xmlObj->Fault) || !isset($xmlObj->Fault->Error)){
return false;
}
return true;
} | php | {
"resource": ""
} |
q255775 | IntuitResponse.setResponseAsItIs | test | private function setResponseAsItIs($passedHeaders, $passedBody, $passedHttpResponseCode){
if(isset($passedHeaders) && isset($passedBody) && isset($passedHttpResponseCode)){
$this->headers = $passedHeaders;
$this->body = $passedBody;
$this->httpResponseCode = $passedHttpResponseCode;
$this->setContentType(CoreConstants::CONTENT_TYPE, $passedHeaders[CoreConstants::CONTENT_TYPE]);
$this->setIntuitTid(CoreConstants::INTUIT_TID, $passedHeaders[CoreConstants::INTUIT_TID]);
$this->setFaultHandler($passedBody, $passedHttpResponseCode, $this->getIntuitTid());
}else{
throw new SdkException("Passed Headers, body, or status code is Null.");
}
} | php | {
"resource": ""
} |
q255776 | IntuitResponse.parseResponseToIntuitResponse | test | private function parseResponseToIntuitResponse($passedHeaders, $passedBody, $passedHttpResponseCode, $clientName){
if($clientName == CoreConstants::CLIENT_CURL){
if(isset($passedHeaders)){
$this->setHeaders($passedHeaders);
}else{
throw new SdkException("The response header from cURL is null.");
}
if(isset($passedBody)){
$this->body = $passedBody;
}else{
throw new SdkException("The Http Response Body from cURL is null.");
}
if(isset($passedHttpResponseCode)){
$this->httpResponseCode = (int)$passedHttpResponseCode;
$this->setFaultHandler($this->getBody(), $this->getStatusCode(), $this->getIntuitTid());
}else{
throw new SdkException("Passed Http status code from cURL is null.");
}
}else{
throw new SdkException("This should not be thrown. IntuitResponse currently don't support parse other client response to Intuit Response other than curl.");
}
} | php | {
"resource": ""
} |
q255777 | IntuitResponse.setFaultHandler | test | private function setFaultHandler($body, $httpResponseCode, $tid){
//If the status code is non-200
if($httpResponseCode < 200 || $httpResponseCode >= 300){
$this->faultHandler = new FaultHandler();
$this->faultHandler->setHttpStatusCode($httpResponseCode);
$this->faultHandler->setResponseBody($body);
$this->faultHandler->setIntuitTid($tid);
//A standard message for now.
//TO DO: Wait V3 Team to provide different message for different response.
$this->faultHandler->setHelpMsg("Invalid auth/bad request (got a " . $httpResponseCode . ", expected HTTP/1.1 20X or a redirect)");
if($this->getResponseContentType() != null && strcasecmp($this->getResponseContentType(), CoreConstants::CONTENTTYPE_APPLICATIONXML) == 0){
$this->faultHandler->parseResponse($body);
}
}else{
$this->faultHandler = false;
}
} | php | {
"resource": ""
} |
q255778 | IntuitResponse.setHeaders | test | public function setHeaders($rawHeaders){
$rawHeaders = str_replace("\r\n", "\n", $rawHeaders);
$response_headers_rows = explode("\n", trim($rawHeaders));
foreach ($response_headers_rows as $line) {
if(strpos($line, ': ') == false){
continue;
}else {
list($key, $value) = explode(': ', $line);
$this->headers[$key] = $value;
//set response content type
$this->setContentType($key, $value);
$this->setIntuitTid($key, $value);
}
}
} | php | {
"resource": ""
} |
q255779 | IntuitResponse.setContentType | test | private function setContentType($key, $val){
$trimedKey = trim($key);
if(strcasecmp($trimedKey, CoreConstants::CONTENT_TYPE) == 0){
$this->contentType = trim($val);
}
} | php | {
"resource": ""
} |
q255780 | IntuitResponse.setIntuitTid | test | private function setIntuitTid($key, $val){
$trimedKey = trim($key);
if(strcasecmp($trimedKey, CoreConstants::INTUIT_TID) == 0){
$this->intuit_tid = trim($val);
}
} | php | {
"resource": ""
} |
q255781 | PlatformService.GetAppMenu | test | public function GetAppMenu()
{
$this->requestXmlDocument = '';
$uriFragment = implode(CoreConstants::SLASH_CHAR, array('v1', 'Account', 'AppMenu'));
$requestParameters = new RequestParameters(null, 'GET', null, $uriFragment);
list($respCode, $respHtml) = $this->restRequestHandler->sendRequest($requestParameters, $this->requestXmlDocument, null);
return $respHtml;
} | php | {
"resource": ""
} |
q255782 | PlatformService.Reconnect | test | public function Reconnect()
{
$this->requestXmlDocument = '';
$uriFragment = implode(CoreConstants::SLASH_CHAR, array('v1', 'Connection', 'Reconnect'));
$requestParameters = new RequestParameters(null, 'GET', null, $uriFragment);
list($respCode, $respXml) = $this->restRequestHandler->sendRequest($requestParameters, $this->requestXmlDocument, null);
return simplexml_load_string($respXml);
} | php | {
"resource": ""
} |
q255783 | Zend_Soap_Wsdl.setUri | test | public function setUri($uri)
{
if ($uri instanceof Zend_Uri_Http) {
$uri = $uri->getUri();
}
$oldUri = $this->_uri;
$this->_uri = $uri;
if ($this->_dom !== null) {
// @todo: This is the worst hack ever, but its needed due to design and non BC issues of WSDL generation
$xml = $this->_dom->saveXML();
$xml = str_replace($oldUri, $uri, $xml);
$this->_dom = new DOMDocument();
$this->_dom->loadXML($xml);
}
return $this;
} | php | {
"resource": ""
} |
q255784 | Zend_Soap_Wsdl.setComplexTypeStrategy | test | public function setComplexTypeStrategy($strategy)
{
if ($strategy === true) {
require_once "Zend/Soap/Wsdl/Strategy/DefaultComplexType.php";
$strategy = new Zend_Soap_Wsdl_Strategy_DefaultComplexType();
} elseif ($strategy === false) {
require_once "Zend/Soap/Wsdl/Strategy/AnyType.php";
$strategy = new Zend_Soap_Wsdl_Strategy_AnyType();
} elseif (is_string($strategy)) {
if (class_exists($strategy)) {
$strategy = new $strategy();
} else {
require_once "Zend/Soap/Wsdl/Exception.php";
throw new Zend_Soap_Wsdl_Exception(
sprintf("Strategy with name '%s does not exist.", $strategy
));
}
}
if (!($strategy instanceof Zend_Soap_Wsdl_Strategy_Interface)) {
require_once "Zend/Soap/Wsdl/Exception.php";
throw new Zend_Soap_Wsdl_Exception("Set a strategy that is not of type 'Zend_Soap_Wsdl_Strategy_Interface'");
}
$this->_strategy = $strategy;
return $this;
} | php | {
"resource": ""
} |
q255785 | Zend_Soap_Wsdl.addBindingOperation | test | public function addBindingOperation($binding, $name, $input = false, $output = false, $fault = false)
{
$operation = $this->_dom->createElement('operation');
$operation->setAttribute('name', $name);
if (is_array($input)) {
$node = $this->_dom->createElement('input');
$soap_node = $this->_dom->createElement('soap:body');
foreach ($input as $name => $value) {
$soap_node->setAttribute($name, $value);
}
$node->appendChild($soap_node);
$operation->appendChild($node);
}
if (is_array($output)) {
$node = $this->_dom->createElement('output');
$soap_node = $this->_dom->createElement('soap:body');
foreach ($output as $name => $value) {
$soap_node->setAttribute($name, $value);
}
$node->appendChild($soap_node);
$operation->appendChild($node);
}
if (is_array($fault)) {
$node = $this->_dom->createElement('fault');
if (isset($fault['name'])) {
$node->setAttribute('name', $fault['name']);
}
$soap_node = $this->_dom->createElement('soap:body');
foreach ($output as $name => $value) {
$soap_node->setAttribute($name, $value);
}
$node->appendChild($soap_node);
$operation->appendChild($node);
}
$binding->appendChild($operation);
return $operation;
} | php | {
"resource": ""
} |
q255786 | Zend_Soap_Wsdl.addDocumentation | test | public function addDocumentation($input_node, $documentation)
{
if ($input_node === $this) {
$node = $this->_dom->documentElement;
} else {
$node = $input_node;
}
$doc = $this->_dom->createElement('documentation');
$doc_cdata = $this->_dom->createTextNode($documentation);
$doc->appendChild($doc_cdata);
if ($node->hasChildNodes()) {
$node->insertBefore($doc, $node->firstChild);
} else {
$node->appendChild($doc);
}
return $doc;
} | php | {
"resource": ""
} |
q255787 | Zend_Soap_Wsdl.addTypes | test | public function addTypes($types)
{
if ($types instanceof DomDocument) {
$dom = $this->_dom->importNode($types->documentElement);
$this->_wsdl->appendChild($types->documentElement);
} elseif ($types instanceof DomNode || $types instanceof DomElement || $types instanceof DomDocumentFragment) {
$dom = $this->_dom->importNode($types);
$this->_wsdl->appendChild($dom);
}
} | php | {
"resource": ""
} |
q255788 | Zend_Soap_Wsdl.addType | test | public function addType($type)
{
if (!in_array($type, $this->_includedTypes)) {
$this->_includedTypes[] = $type;
}
return $this;
} | php | {
"resource": ""
} |
q255789 | Zend_Soap_Wsdl.dump | test | public function dump($filename = false)
{
if (!$filename) {
echo $this->toXML();
return true;
} else {
return file_put_contents($filename, $this->toXML());
}
} | php | {
"resource": ""
} |
q255790 | Zend_Soap_Wsdl.addSchemaTypeSection | test | public function addSchemaTypeSection()
{
if ($this->_schema === null) {
$this->_schema = $this->_dom->createElement('xsd:schema');
$this->_schema->setAttribute('targetNamespace', $this->_uri);
$types = $this->_dom->createElement('types');
$types->appendChild($this->_schema);
$this->_wsdl->appendChild($types);
}
return $this;
} | php | {
"resource": ""
} |
q255791 | ServiceContext.ConfigureFromPassedArray | test | public static function ConfigureFromPassedArray(array $settings)
{
ServiceContext::checkIfOAuthIsValid($settings);
if(strcasecmp($settings['auth_mode'], CoreConstants::OAUTH1) == 0) {
$OAuthConfig = new OAuthRequestValidator(
$settings['accessTokenKey'],
$settings['accessTokenSecret'],
$settings['consumerKey'],
$settings['consumerSecret']
);
}else{
$OAuthConfig = new OAuth2AccessToken(
$settings['ClientID'],
$settings['ClientSecret'],
CoreConstants::getAccessTokenFromArray($settings),
CoreConstants::getRefreshTokenFromArray($settings)
);
}
$QBORealmID = array_key_exists('QBORealmID', $settings) ? $settings['QBORealmID'] : null;
$baseURL = array_key_exists('baseUrl', $settings) ? $settings['baseUrl']: null;
if(strcasecmp($baseURL, CoreConstants::DEVELOPMENT_SANDBOX) == 0){
$baseURL = CoreConstants::SANDBOX_DEVELOPMENT;
}else if(strcasecmp($baseURL, CoreConstants::PRODUCTION_QBO) == 0){
$baseURL = CoreConstants::QBO_BASEURL;
}
$checkedBaseURL = ServiceContext::checkAndAddBaseURLSlash($baseURL);
if($OAuthConfig instanceof OAuth2AccessToken){
$OAuthConfig->setRealmID($QBORealmID);
$OAuthConfig->setBaseURL($checkedBaseURL);
}
$serviceType = CoreConstants::IntuitServicesTypeQBO;
$IppConfiguration = LocalConfigReader::ReadConfigurationFromParameters($OAuthConfig, $checkedBaseURL, CoreConstants::DEFAULT_LOGGINGLOCATION, CoreConstants::DEFAULT_SDK_MINOR_VERSION);
$serviceContextInstance = new ServiceContext($QBORealmID, $serviceType, $OAuthConfig, $IppConfiguration);
return $serviceContextInstance;
} | php | {
"resource": ""
} |
q255792 | ServiceContext.checkIfOAuthIsValid | test | public static function checkIfOAuthIsValid(array $settings){
if (!isset($settings) || empty($settings)) {
throw new SdkException("Empty OAuth Array passed. Can't construct ServiceContext based on Empty Array.");
}
if(!isset($settings['auth_mode'])){
throw new SdkException("No OAuth 1 or OAuth 2 Mode specified. Can't validate OAuth tokens.");
}
$mode = $settings['auth_mode'];
//OAuth 1 settings, OAuth 1 must provide all four values.
if (strcasecmp($mode, CoreConstants::OAUTH1) == 0) {
if (!isset($settings['accessTokenKey'])) {
throw new SdkException("'accessTokenKey' must be provided in OAuth1.");
}
if (!isset($settings['accessTokenSecret'])) {
throw new SdkException("'accessTokenSecret' must be provided in OAuth1.");
}
}
//OAuth 2 settings, Only client ID and Client Secret is required. For making API call, all four values, Client ID, Client Secret, Access Token, Access Token Secret are required.
else if(strcasecmp($mode, CoreConstants::OAUTH2) == 0){
if (!isset($settings['ClientID'])) {
throw new SdkException("'ClientID' must be provided in OAuth2.");
}
if (!isset($settings['ClientSecret'])) {
throw new SdkException("'ClientSecret' must be provided in OAuth2.");
}
}
//Now other OAuth is supported
else{
throw new SdkException("OAuth Mode is not supported.");
}
} | php | {
"resource": ""
} |
q255793 | ServiceContext.getBaseURL | test | public function getBaseURL()
{
$this->IppConfiguration->Logger->RequestLog->Log(TraceLevel::Info, "Called GetBaseURL method.");
try {
if ($this->serviceType === CoreConstants::IntuitServicesTypeQBO) {
$baseurl = $this->IppConfiguration->BaseUrl->Qbo . implode(CoreConstants::SLASH_CHAR, array(CoreConstants::VERSION)) . CoreConstants::SLASH_CHAR;
}
else if($this->serviceType === CoreConstants::IntuitServicesTypeIPP){
$this->IppConfiguration->BaseUrl->Ipp = CoreConstants::IPP_BASEURL;
$baseurl = $this->IppConfiguration->BaseUrl->Ipp;
}
} catch (\Exception $e) {
throw new \Exception("Base URL is not setup");
}
return $baseurl;
} | php | {
"resource": ""
} |
q255794 | ServiceContext.useXml | test | public function useXml()
{
$this->IppConfiguration->Message->Request->CompressionFormat = CompressionFormat::None;
$this->IppConfiguration->Message->Response->CompressionFormat = CompressionFormat::None;
$this->IppConfiguration->Message->Request->SerializationFormat = SerializationFormat::Xml;
$this->IppConfiguration->Message->Response->SerializationFormat = SerializationFormat::Xml;
} | php | {
"resource": ""
} |
q255795 | ServiceContext.useJson | test | public function useJson()
{
$this->IppConfiguration->Message->Request->CompressionFormat = CompressionFormat::None;
$this->IppConfiguration->Message->Response->CompressionFormat = CompressionFormat::None;
$this->IppConfiguration->Message->Request->SerializationFormat = SerializationFormat::Json;
$this->IppConfiguration->Message->Response->SerializationFormat = SerializationFormat::Json;
} | php | {
"resource": ""
} |
q255796 | ServiceContext.disableLog | test | public function disableLog()
{
try {
$_ippConfigInstance = $this->getIppConfig();
LocalConfigReader::setupLogger($_ippConfigInstance, CoreConstants::DEFAULT_LOGGINGLOCATION, "FALSE");
} catch (\Exception $e) {
throw new \Exception("Error in disable Log.");
}
} | php | {
"resource": ""
} |
q255797 | ServiceContext.setLogLocation | test | public function setLogLocation($new_log_location)
{
try {
$_ippConfigInstance = $this->getIppConfig();
LocalConfigReader::setupLogger($_ippConfigInstance, $new_log_location, "TRUE");
} catch (\Exception $e) {
throw new \Exception("Error in setting up new Log Configuration: " . $new_log_location);
}
} | php | {
"resource": ""
} |
q255798 | ServiceContext.updateOAuth2Token | test | public function updateOAuth2Token($OAuth2AccessToken){
if($OAuth2AccessToken instanceof OAuth2AccessToken && $this->requestValidator instanceof OAuth2AccessToken){
$this->IppConfiguration->Security = $OAuth2AccessToken;
$this->requestValidator = $OAuth2AccessToken;
}
} | php | {
"resource": ""
} |
q255799 | PHPClass.getClassProperties | test | public function getClassProperties($props, $indent = "\t")
{
$code = $indent."\n";
foreach ($props as $prop) {
if (!empty($prop['docs'])) {
$code .= $indent.$this->getDocBlock($prop['docs'], $indent);
}
$code .= $indent.'public $'.$prop['name'].";\n";
}
return $code;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.