Example #1
0
 /**
  * Common function to handle exceptions in the data service.
  * 
  * @param Exception   $exception    exception occured
  * @param DataService &$dataService dataservice
  * 
  * @return nothing
  */
 public static function handleException($exception, DataService &$dataService)
 {
     $acceptTypesText = $dataService->getHost()->getRequestAccept();
     $responseContentType = null;
     try {
         $responseContentType = HttpProcessUtility::selectMimeType($acceptTypesText, array(ODataConstants::MIME_APPLICATION_XML, ODataConstants::MIME_APPLICATION_JSON));
     } catch (HttpHeaderFailure $exception) {
         $exception = new ODataException($exception->getMessage(), $exception->getStatusCode());
     } catch (\Exception $exception) {
         // Never come here
     }
     if (is_null($responseContentType)) {
         $responseContentType = ODataConstants::MIME_APPLICATION_XML;
     }
     if (!$exception instanceof ODataException) {
         $exception = new ODataException($exception->getMessage(), HttpStatus::CODE_INTERNAL_SERVER_ERROR);
     }
     $dataService->getHost()->setResponseVersion(ODataConstants::DATASERVICEVERSION_1_DOT_0 . ';');
     // At this point all kind of exceptions will be converted
     //to 'ODataException'
     if ($exception->getStatusCode() == HttpStatus::CODE_NOT_MODIFIED) {
         $dataService->getHost()->setResponseStatusCode(HttpStatus::CODE_NOT_MODIFIED);
     } else {
         $dataService->getHost()->setResponseStatusCode($exception->getStatusCode());
         $dataService->getHost()->setResponseContentType($responseContentType);
         $responseBody = null;
         if (strcasecmp($responseContentType, ODataConstants::MIME_APPLICATION_XML) == 0) {
             $responseBody = AtomODataWriter::serializeException($exception, true);
         } else {
             $responseBody = JsonODataWriter::serializeException($exception, true);
         }
         $dataService->getHost()->getWebOperationContext()->outgoingResponse()->setStream($responseBody);
     }
 }
 public function handleRequest()
 {
     try {
         $this->createProviders();
         $this->getHost()->validateQueryParameters();
         $requestMethod = $this->getOperationContext()->incomingRequest()->getMethod();
         if ($requestMethod !== ODataConstants::HTTP_METHOD_GET) {
             ODataException::createNotImplementedError(Messages::dataServiceOnlyReadSupport($requestMethod));
         }
     } catch (\Exception $exception) {
         throw $exception;
     }
     $uriProcessor = null;
     try {
         $uriProcessor = UriProcessor::process($this);
         return $uriProcessor;
     } catch (\Exception $exception) {
         throw $exception;
     }
 }
Example #3
0
 /**
  * Sets the value status code header on the response
  * 
  * @param string $value The status code
  * 
  * @return void
  */
 public function setResponseStatusCode($value)
 {
     $floor = floor($value / 100);
     if ($floor >= 1 && $floor <= 5) {
         $statusDescription = HttpStatus::getStatusDescription($value);
         if (!is_null($statusDescription)) {
             $statusDescription = ' ' . $statusDescription;
         }
         $this->_operationContext->outgoingResponse()->setStatusCode($value . $statusDescription);
     } else {
         ODataException::createInternalServerError('Invalid Status Code' . $value);
     }
 }
 /**
  * Process the given request Uri and creates an instance of 
  * RequestDescription from the processed uri.
  * 
  * @param Url         &$absoluteRequestUri The absolute request uri.
  * @param DataService &$dataService        Reference to the data service
  *                                         instance.
  * 
  * @return RequestDescription
  * 
  * @throws ODataException If any exception occurs while processing the segments
  *                        or incase of any version incompatibility.
  */
 public static function process(Url &$absoluteRequestUri, DataService &$dataService)
 {
     $absoluteRequestUri = $dataService->getHost()->getAbsoluteRequestUri();
     $absoluteServiceUri = $dataService->getHost()->getAbsoluteServiceUri();
     $requestUriSegments = array_slice($absoluteRequestUri->getSegments(), $absoluteServiceUri->getSegmentCount());
     $segmentDescriptors = null;
     try {
         $segmentDescriptors = SegmentParser::parseRequestUriSegements($requestUriSegments, $dataService->getMetadataQueryProviderWrapper(), true);
     } catch (ODataException $odataException) {
         throw $odataException;
     }
     $requestDescription = new RequestDescription($segmentDescriptors, $absoluteRequestUri);
     $requestTargetKind = $requestDescription->getTargetKind();
     if ($requestTargetKind != RequestTargetKind::METADATA && $requestTargetKind != RequestTargetKind::BATCH && $requestTargetKind != RequestTargetKind::SERVICE_DIRECTORY) {
         if ($requestTargetKind != RequestTargetKind::PRIMITIVE_VALUE && $requestTargetKind != RequestTargetKind::MEDIA_RESOURCE) {
             $requestDescription->setContainerName($requestDescription->getIdentifier());
         } else {
             // http://odata/NW.svc/Orders/$count
             // http://odata/NW.svc/Orders(123)/Customer/CustomerID/$value
             // http://odata/NW.svc/Employees(1)/$value
             // http://odata/NW.svc/Employees(1)/ThumbNail_48X48/$value
             $requestDescription->setContainerName($segmentDescriptors[count($segmentDescriptors) - 2]->getIdentifier());
         }
         if ($requestDescription->getIdentifier() === ODataConstants::URI_COUNT_SEGMENT) {
             if (!$dataService->getServiceConfiguration()->getAcceptCountRequests()) {
                 ODataException::createBadRequestError(Messages::dataServiceConfigurationCountNotAccepted());
             }
             $requestDescription->setRequestCountOption(RequestCountOption::VALUE_ONLY);
             // use of $count requires request DataServiceVersion
             // and MaxDataServiceVersion
             // greater than or equal to 2.0
             $requestDescription->raiseResponseVersion(2, 0, $dataService);
             $requestDescription->raiseMinimumVersionRequirement(2, 0, $dataService);
         } else {
             if ($requestDescription->isNamedStream()) {
                 $requestDescription->raiseMinimumVersionRequirement(3, 0, $dataService);
             } else {
                 if ($requestDescription->getTargetKind() == RequestTargetKind::RESOURCE) {
                     if (!$requestDescription->isLinkUri()) {
                         $resourceSetWrapper = $requestDescription->getTargetResourceSetWrapper();
                         //assert($resourceSetWrapper != null)
                         $hasNamedStream = $resourceSetWrapper->hasNamedStreams($dataService->getMetadataQueryProviderWrapper());
                         $hasBagProperty = $resourceSetWrapper->hasBagProperty($dataService->getMetadataQueryProviderWrapper());
                         if ($hasNamedStream || $hasBagProperty) {
                             $requestDescription->raiseResponseVersion(3, 0, $dataService);
                         }
                     }
                 } else {
                     if ($requestDescription->getTargetKind() == RequestTargetKind::BAG) {
                         $requestDescription->raiseResponseVersion(3, 0, $dataService);
                     }
                 }
             }
         }
     }
     return $requestDescription;
 }
 /**
  * Write all resource types (entity and complex types)
  * 
  * @param array $resourceTypes                            resource types array
  * array(ResourceType)
  * @param array $associationTypesInResourceTypesNamespace collection of 
  * association types for the given resource types
  * array(string, AssociationType)
  * 
  * @return nothing
  */
 private function _writeResourceTypes($resourceTypes, $associationTypesInResourceTypesNamespace)
 {
     foreach ($resourceTypes as $resourceType) {
         if ($resourceType->getResourceTypeKind() == ResourceTypeKind::ENTITY) {
             $this->_writeEntityType($resourceType, $associationTypesInResourceTypesNamespace);
         } else {
             if ($resourceType->getResourceTypeKind() == ResourceTypeKind::COMPLEX) {
                 $this->_writeComplexType($resourceType);
             } else {
                 ODataException::createInternalServerError(Messages::metadataWriterExpectingEntityOrComplexResourceType());
             }
         }
     }
 }
Example #6
0
 /**
  * Returns the etag for the given resource.
  * Note: This function will not add W\" prefix and " suffix, its callers
  * repsonsability.
  *
  * @param mixed        &$entryObject  Resource for which etag value needs to 
  *                                    be returned
  * @param ResourceType &$resourceType Resource type of the $entryObject
  * 
  * @return string/NULL ETag value for the given resource (with values encoded 
  *                     for use in a URI) there are etag properties, NULL if 
  *                     there is no etag property.
  */
 protected function getETagForEntry(&$entryObject, ResourceType &$resourceType)
 {
     $eTag = null;
     $comma = null;
     foreach ($resourceType->getETagProperties() as $eTagProperty) {
         $type = $eTagProperty->getInstanceType();
         self::assert(!is_null($type) && array_search('ODataProducer\\Providers\\Metadata\\Type\\IType', class_implements($type)) !== false, '!is_null($type) 
             && array_search(\'ODataProducer\\Providers\\Metadata\\Type\\IType\', class_implements($type)) !== false');
         $value = null;
         try {
             $reflectionProperty = new \ReflectionProperty($entryObject, $eTagProperty->getName());
             $value = $reflectionProperty->getValue($entryObject);
         } catch (\ReflectionException $reflectionException) {
             throw ODataException::createInternalServerError(Messages::dataServiceFailedToAccessProperty($eTagProperty->getName(), $resourceType->getName()));
         }
         if (is_null($value)) {
             $eTag = $eTag . $comma . 'null';
         } else {
             $eTag = $eTag . $comma . $type->convertToOData($value);
         }
         $comma = ',';
     }
     if (!is_null($eTag)) {
         // If eTag is made up of datetime or string properties then the above
         // IType::converToOData will perform utf8 and url encode. But we don't
         // want this for eTag value.
         $eTag = urldecode(utf8_decode($eTag));
         return rtrim($eTag, ',');
     }
     return null;
 }
Example #7
0
 /**
  *  Populate map table 
  *
  * @param AbstractExpression $nullCheckExpTree The expression to verfiy.
  * 
  * @return void
  * 
  * @throws ODataException
  */
 private function _map($nullCheckExpTree)
 {
     if ($nullCheckExpTree instanceof LogicalExpression) {
         $this->_map($nullCheckExpTree->getLeft());
         $this->_map($nullCheckExpTree->getRight());
     } else {
         if ($nullCheckExpTree instanceof UnaryExpression) {
             $this->_map($nullCheckExpTree->getChild());
         } else {
             if ($nullCheckExpTree instanceof FunctionCallExpression) {
                 $param = $nullCheckExpTree->getParamExpressions();
                 $this->_map($param[0]);
             } else {
                 if ($nullCheckExpTree instanceof PropertyAccessExpression) {
                     $parent = $nullCheckExpTree;
                     $key = null;
                     do {
                         $key = $parent->getResourceProperty()->getName() . '_' . $key;
                         $parent = $parent->getParent();
                     } while ($parent != null);
                     $this->_mapTable[$key] = $nullCheckExpTree;
                 } else {
                     ODataException::createSyntaxError(Messages::expressionParser2UnexpectedExpression(get_class($expTree)));
                 }
             }
         }
     }
 }
 /**
  * Get related resource for a resource
  *
  * @param ResourceSet      $sourceResourceSet    The source resource set
  * @param mixed            $sourceEntityInstance The source resource
  * @param ResourceSet      $targetResourceSet    The resource set of
  *                                               the navigation property
  * @param ResourceProperty $targetProperty       The navigation property to be
  *                                               retrieved
  *
  * @return Object/null The related resource if exists else null
  */
 public function getRelatedResourceReference(ResourceSet $sourceResourceSet, $sourceEntityInstance, ResourceSet $targetResourceSet, ResourceProperty $targetProperty)
 {
     ODataException::createNotImplementedError($this->_message);
 }
 /**
  * Get the value of a given property from an instance.
  * 
  * @param mixed            &$object           Instance of a type which 
  *                                            contains this property. 
  * @param ResourceType     &$resourceType     Resource type instance 
  *                                            containing metadata about 
  *                                            the instance.
  * @param ResourceProperty &$resourceProperty Resource property instance 
  *                                            containing metadata about the 
  *                                            property whose value 
  *                                            to be retrieved.
  * 
  * @return mixed The value of the given property.
  * 
  * @throws ODataException If reflection exception occured 
  * while trying to access the property.
  */
 protected function getPropertyValue(&$object, ResourceType &$resourceType, ResourceProperty &$resourceProperty)
 {
     try {
         $reflectionProperty = new \ReflectionProperty($object, $resourceProperty->getName());
         $propertyValue = $reflectionProperty->getValue($object);
         return $propertyValue;
     } catch (\ReflectionException $reflectionException) {
         throw ODataException::createInternalServerError(Messages::objectModelSerializerFailedToAccessProperty($resourceProperty->getName(), $resourceType->getName()));
     }
 }
 /**
  * Modify the 'Projection Tree' to include selection details
  * 
  * @param array(array(string)) $selectPathSegments Collection of select 
  *                                                 paths.
  * 
  * @return void
  * 
  * @throws ODataException If any error occurs while processing select
  *                        path segments
  */
 private function _applySelectionToProjectionTree($selectPathSegments)
 {
     foreach ($selectPathSegments as $selectSubPathSegments) {
         $currentNode = $this->_rootProjectionNode;
         $subPathCount = count($selectSubPathSegments);
         foreach ($selectSubPathSegments as $index => $selectSubPathSegment) {
             if (!$currentNode instanceof RootProjectionNode && !$currentNode instanceof ExpandedProjectionNode) {
                 ODataException::createBadRequestError(Messages::expandProjectionParserPropertyWithoutMatchingExpand($currentNode->getPropertyName()));
             }
             $currentNode->setSelectionFound();
             $isLastSegment = $index == $subPathCount - 1;
             if ($selectSubPathSegment === '*') {
                 $currentNode->setSelectAllImmediateProperties();
                 break;
             }
             $currentResourceType = $currentNode->getResourceType();
             $resourceProperty = $currentResourceType->tryResolvePropertyTypeByName($selectSubPathSegment);
             if (is_null($resourceProperty)) {
                 ODataException::createSyntaxError(Messages::expandProjectionParserPropertyNotFound($currentResourceType->getFullName(), $selectSubPathSegment, true));
             }
             if (!$isLastSegment) {
                 if ($resourceProperty->isKindOf(ResourcePropertyKind::BAG)) {
                     ODataException::createBadRequestError(Messages::expandProjectionParserBagPropertyAsInnerSelectSegment($currentResourceType->getFullName(), $selectSubPathSegment));
                 } else {
                     if ($resourceProperty->isKindOf(ResourcePropertyKind::PRIMITIVE)) {
                         ODataException::createBadRequestError(Messages::expandProjectionParserPrimitivePropertyUsedAsNavigationProperty($currentResourceType->getFullName(), $selectSubPathSegment));
                     } else {
                         if ($resourceProperty->isKindOf(ResourcePropertyKind::COMPLEX_TYPE)) {
                             ODataException::createBadRequestError(Messages::expandProjectionParserComplexPropertyAsInnerSelectSegment($currentResourceType->getFullName(), $selectSubPathSegment));
                         } else {
                             if ($resourceProperty->getKind() != ResourcePropertyKind::RESOURCE_REFERENCE && $resourceProperty->getKind() != ResourcePropertyKind::RESOURCESET_REFERENCE) {
                                 ODataException::createInternalServerError(Messages::expandProjectionParserUnexpectedPropertyType());
                             }
                         }
                     }
                 }
             }
             $node = $currentNode->findNode($selectSubPathSegment);
             if (is_null($node)) {
                 if (!$isLastSegment) {
                     ODataException::createBadRequestError(Messages::expandProjectionParserPropertyWithoutMatchingExpand($selectSubPathSegment));
                 }
                 $node = new ProjectionNode($selectSubPathSegment, $resourceProperty);
                 $currentNode->addNode($node);
             }
             $currentNode = $node;
             if ($currentNode instanceof ExpandedProjectionNode && $isLastSegment) {
                 $currentNode->setSelectionFound();
                 $currentNode->markSubtreeAsSelected();
             }
         }
     }
 }
Example #11
0
 /**
  * Validates the given version in string format and returns the version as instance of Version
  * 
  * @param string $versionHeader The DataServiceVersion or MaxDataServiceVersion header value
  * @param string $headerName    The name of the header
  * 
  * @return Version
  * 
  * @throws ODataException If the version is malformed or not supported
  */
 private static function _validateAndGetVersion($versionHeader, $headerName)
 {
     $libName = null;
     $versionHeader = trim($versionHeader);
     $libNameIndex = strpos($versionHeader, ';');
     if ($libNameIndex !== false) {
         $libName = substr($versionHeader, $libNameIndex);
     } else {
         $libNameIndex = strlen($versionHeader);
     }
     $dotIndex = -1;
     for ($i = 0; $i < $libNameIndex; $i++) {
         if ($versionHeader[$i] == '.') {
             if ($dotIndex != -1) {
                 ODataException::createBadRequestError(Messages::requestDescriptionInvalidVersionHeader($versionHeader, $headerName));
             }
             $dotIndex = $i;
         } else {
             if ($versionHeader[$i] < '0' || $versionHeader[$i] > '9') {
                 ODataException::createBadRequestError(Messages::requestDescriptionInvalidVersionHeader($versionHeader, $headerName));
             }
         }
     }
     $major = $minor = 0;
     if ($dotIndex != -1) {
         if ($dotIndex == 0) {
             ODataException::createBadRequestError(Messages::requestDescriptionInvalidVersionHeader($versionHeader, $headerName));
         }
         $major = intval(substr($versionHeader, 0, $dotIndex));
         $minor = intval(substr($versionHeader, $dotIndex + 1, $libNameIndex));
     } else {
         $major = intval(substr($versionHeader, 0, $dotIndex));
         $minor = 0;
     }
     $version = new Version($major, $minor);
     $isSupportedVersion = false;
     foreach (self::getKnownDataServiceVersions() as $version1) {
         if ($version->compare($version1) == 0) {
             $isSupportedVersion = true;
             break;
         }
     }
     if (!$isSupportedVersion) {
         $availableVersions = null;
         foreach (self::getKnownDataServiceVersions() as $version1) {
             $availableVersions .= $version1->toString() . ', ';
         }
         $availableVersions = rtrim($availableVersions, ', ');
         ODataException::createBadRequestError(Messages::requestDescriptionUnSupportedVersion($headerName, $versionHeader, $availableVersions));
     }
     return $version;
 }
Example #12
0
 /**
  * Checks whether this request has the specified rights
  * 
  * @param EntitySetRights $requiredRights The rights to check
  * 
  * @return void
  * 
  * @throws ODataException exception if access to this resource set is forbidden
  */
 public function checkResourceSetRights($requiredRights)
 {
     if (($this->_resourceSetRights & $requiredRights) == 0) {
         ODataException::createForbiddenError();
     }
 }
Example #13
0
 /**
  * Assert that the given condition is true, if false throw 
  * ODataException for unexpected state
  * 
  * @param boolean $condition The condition to assert
  * 
  * @return void
  * 
  * @throws ODataException
  */
 private function _assertion($condition)
 {
     if (!$condition) {
         ODataException::createInternalServerError(Messages::orderByParserUnExpectedState());
     }
 }
 /**
  * Serialize the exception
  *
  * @param ODataException &$exception              Exception to serialize
  * @param boolean        $serializeInnerException if set to true,
  * serialize the inner exception if $exception is an ODataException.
  * 
  * @return nothing
  */
 public static function serializeException(ODataException &$exception, $serializeInnerException)
 {
     $xmlWriter = new \XMLWriter();
     $xmlWriter->openMemory();
     $xmlWriter->startDocument('1.0', 'UTF-8', 'yes');
     $xmlWriter->setIndent(4);
     $xmlWriter->startElement(ODataConstants::XML_ERROR_ELEMENT_NAME);
     //$xmlWriter->writeAttributeNs(
     //    ODataConstants::XMLNS_NAMESPACE_PREFIX,
     //    ODataConstants::XML_NAMESPACE_PREFIX,
     //    ODataConstants::XML_NAMESPACE,
     //    null
     //);
     $xmlWriter->writeAttribute(ODataConstants::XMLNS_NAMESPACE_PREFIX, ODataConstants::ODATA_METADATA_NAMESPACE);
     $xmlWriter->endAttribute();
     $xmlWriter->startElement(ODataConstants::XML_ERROR_CODE_ELEMENT_NAME);
     if ($exception->getCode() != null) {
         $xmlWriter->text($exception->getCode());
     }
     $xmlWriter->endElement();
     $xmlWriter->startElement(ODataConstants::XML_ERROR_MESSAGE_ELEMENT_NAME);
     $xmlWriter->text($exception->getMessage());
     $xmlWriter->endElement();
     $xmlWriter->endElement();
     $xmlWriter->endDocument();
     return $xmlWriter->outputMemory(true);
 }
 /**
  * The clone method is private, so it can't be call from outside of the class
  * 
  * @return void
  * 
  * $throws Exception if developer try to make a clone of WebOperationContext 
  *                   class.
  */
 public function __clone()
 {
     throw ODataException::notAcceptableError("Cloning of WebOperationContext is not allowed!!!");
 }
 /**
  * Validate operands (arguments) of a function call operation and return
  * matching function
  *
  * @param array(FunctionDescription) $functions       List of functions to
  *                                                    be checked
  * @param array(AbstractExpression)  $argExpressions  Function argument
  *                                                    expressions
  * @param ExpressionToken            $expressionToken Expression token
  *
  * @throws ODataException
  *
  * @return FunctionDescription
  */
 public static function verifyFunctionCallOpArguments($functions, $argExpressions, $expressionToken)
 {
     $function = self::findFunctionWithPromotion($functions, $argExpressions, false);
     if ($function == null) {
         $protoTypes = null;
         foreach ($functions as $function) {
             $protoTypes .= $function->getProtoTypeAsString() . '; ';
         }
         ODataException::createSyntaxError(Messages::expressionLexerNoApplicableFunctionsFound($expressionToken->Text, $protoTypes, $expressionToken->Position));
     }
     return $function;
 }
 /**
  * Validate the given entity instance.
  * 
  * @param object        $entityInstance Entity instance to validate
  * @param ResourceSet   &$resourceSet   Resource set to which the entity 
  *                                      instance belongs to.
  * @param KeyDescriptor &$keyDescriptor The key descriptor.
  * @param string        $methodName     Method from which this function 
  *                                      invoked.
  *
  * @return void
  * 
  * @throws ODataException
  */
 private function _validateEntityInstance($entityInstance, ResourceSet &$resourceSet, KeyDescriptor &$keyDescriptor, $methodName)
 {
     if (is_null($entityInstance)) {
         ODataException::createResourceNotFoundError($resourceSet->getName());
     }
     $entityName = $resourceSet->getResourceType()->getInstanceType()->getName();
     if (!is_object($entityInstance) || !$entityInstance instanceof $entityName) {
         ODataException::createInternalServerError(Messages::metadataQueryProviderWrapperIDSQPMethodReturnsUnExpectedType($entityName, $methodName));
     }
     foreach ($keyDescriptor->getValidatedNamedValues() as $keyName => $valueDescription) {
         try {
             $keyProperty = new \ReflectionProperty($entityInstance, $keyName);
             $keyValue = $keyProperty->getValue($entityInstance);
             if (is_null($keyValue)) {
                 ODataException::createInternalServerError(Messages::metadataQueryProviderWrapperIDSQPMethodReturnsInstanceWithNullKeyProperties($methodName));
             }
             $convertedValue = $valueDescription[1]->convert($valueDescription[0]);
             if ($keyValue != $convertedValue) {
                 ODataException::createInternalServerError(Messages::metadataQueryProviderWrapperIDSQPMethodReturnsInstanceWithNonMatchingKeys($methodName));
             }
         } catch (\ReflectionException $reflectionException) {
             //throw ODataException::createInternalServerError(
             //  Messages::orderByParserFailedToAccessOrInitializeProperty(
             //      $resourceProperty->getName(), $resourceType->getName()
             //  )
             //);
         }
     }
 }
 /**
  * Increment recursion count and throw error if beyond limit
  *
  * @return void
  *
  * @throws ODataException If max recursion limit hits.
  */
 private function _recurseEnter()
 {
     $this->_recursionDepth++;
     if ($this->_recursionDepth == self::RECURSION_LIMIT) {
         ODataException::createSyntaxError("Recursion limit reached.");
     }
 }
Example #19
0
 /**
  * Gets the current identifier text
  * 
  * @return string
  */
 public function getIdentifier()
 {
     if ($this->Id != ExpressionTokenId::IDENTIFIER) {
         ODataException::createSyntaxError('Identifier expected at position ' . $this->Position);
     }
     return $this->Text;
 }
Example #20
0
 /**
  * Throws parser error.
  * 
  * @param string $message The error message.
  * 
  * @return void
  * 
  * @throws ODataException
  */
 private function _parseError($message)
 {
     ODataException::createSyntaxError($message);
 }
Example #21
0
 /**
  * serialize exception.
  * 
  * @param ODataException &$exception              Exception to serialize
  * @param Boolean        $serializeInnerException if set to true
  * 
  * serialize the inner exception if $exception is an ODataException.
  * 
  * @return void  
  */
 public static function serializeException(ODataException &$exception, $serializeInnerException)
 {
     $writer = new JsonWriter('');
     // Wrapper for error.
     $writer->startObjectScope();
     // "error"
     $writer->writeName(ODataConstants::JSON_ERROR);
     $writer->startObjectScope();
     // "code"
     if ($exception->getCode() != null) {
         $writer->writeName(ODataConstants::JSON_ERROR_CODE);
         $writer->writeValue($exception->getCode());
     }
     // "message"
     $writer->writeName(ODataConstants::JSON_ERROR_MESSAGE);
     $writer->startObjectScope();
     // "lang"
     $writer->writeName(ODataConstants::XML_LANG_ATTRIBUTE_NAME);
     //if ($exception->getMsgLang() != null) {
     $writer->writeValue('en-US');
     //}
     // "value"
     $writer->writeName(ODataConstants::JSON_ERROR_VALUE);
     $writer->writeValue($exception->getMessage());
     $writer->endScope();
     $writer->endScope();
     $writer->endScope();
     return $writer->getJsonOutput();
 }
Example #22
0
 /**
  * Validate this KeyDescriptor, If valid, this function populates
  * _validatedNamedValues array with key as keyName and value as an array of
  * key value and key type.
  *
  * @param string       $segmentAsString The segment in the form identifer
  *                                      (keyPredicate) which this descriptor
  *                                      represents
  * @param ResourceType $resourceType    The type of the idenfier in the segment
  *
  * @return void
  *
  * @throws ODataException If validation fails.
  */
 public function validate($segmentAsString, ResourceType $resourceType)
 {
     if ($this->isEmpty()) {
         $this->_validatedNamedValues = array();
         return;
     }
     $keyProperties = $resourceType->getKeyProperties();
     $keyPropertiesCount = count($keyProperties);
     if (!empty($this->_namedValues)) {
         if (count($this->_namedValues) != $keyPropertiesCount) {
             ODataException::createSyntaxError(Messages::keyDescriptorKeyCountNotMatching($segmentAsString, $keyPropertiesCount, count($this->_namedValues)));
         }
         foreach ($keyProperties as $keyName => $keyResourceProperty) {
             if (!array_key_exists($keyName, $this->_namedValues)) {
                 $keysAsString = null;
                 foreach (array_keys($keyProperties) as $key) {
                     $keysAsString .= $key . ', ';
                 }
                 $keysAsString = rtrim($keysAsString, ' ,');
                 ODataException::createSyntaxError(Messages::keyDescriptorMissingKeys($segmentAsString, $keysAsString));
             }
             $typeProvided = $this->_namedValues[$keyName][1];
             $expectedType = $keyResourceProperty->getInstanceType();
             if (!$expectedType->isCompatibleWith($typeProvided)) {
                 ODataException::createSyntaxError(Messages::keyDescriptorInCompatibleKeyType($segmentAsString, $keyName, $expectedType->getFullTypeName(), $typeProvided->getFullTypeName()));
             }
             $this->_validatedNamedValues[$keyName] = $this->_namedValues[$keyName];
         }
     } else {
         if (count($this->_positionalValues) != $keyPropertiesCount) {
             ODataException::createSyntaxError(Messages::keyDescriptorKeyCountNotMatching($segmentAsString, $keyPropertiesCount, count($this->_positionalValues)));
         }
         $i = 0;
         foreach ($keyProperties as $keyName => $keyResourceProperty) {
             $typeProvided = $this->_positionalValues[$i][1];
             $expectedType = $keyResourceProperty->getInstanceType();
             if (!$expectedType->isCompatibleWith($typeProvided)) {
                 ODataException::createSyntaxError(Messages::keyDescriptorInCompatibleKeyTypeAtPosition($segmentAsString, $keyResourceProperty->getName(), $i, $expectedType->getFullTypeName(), $typeProvided->getFullTypeName()));
             }
             $this->_validatedNamedValues[$keyName] = $this->_positionalValues[$i];
             $i++;
         }
     }
 }
 /**
  * Write values of properties of given entry (resource) or complex object.
  *
  * @param mixed                $customObject          Entity or complex object
  *                                                    with properties
  *                                                    to write out.
  * @param ResourceType         &$resourceType         Resource type describing
  *                                                    the metadata of
  *                                                    the custom object.
  * @param string               $absoluteUri           Absolute uri for the given
  *                                                    entry object
  *                                                    NULL for complex object.
  * @param string               $relativeUri           Relative uri for the given
  *                                                    custom object.
  * @param ODataEntry           &$odataEntry           ODataEntry instance to
  *                                                    place links and
  *                                                    expansion of the
  *                                                    entry object,
  *                                                    NULL for complex object.
  * @param ODataPropertyContent &$odataPropertyContent ODataPropertyContent
  *                                                    instance in which
  *                                                    to place the values.
  *
  * @return void
  */
 private function _writeObjectProperties($customObject, ResourceType &$resourceType, $absoluteUri, $relativeUri, &$odataEntry, ODataPropertyContent &$odataPropertyContent)
 {
     $resourceTypeKind = $resourceType->getResourceTypeKind();
     if (is_null($absoluteUri) == ($resourceTypeKind == ResourceTypeKind::ENTITY)) {
         ODataException::createInternalServerError(Messages::badProviderInconsistentEntityOrComplexTypeUsage($resourceType->getName()));
     }
     $this->assert($resourceTypeKind == ResourceTypeKind::ENTITY && $odataEntry instanceof ODataEntry || $resourceTypeKind == ResourceTypeKind::COMPLEX && is_null($odataEntry), '(($resourceTypeKind == ResourceTypeKind::ENTITY) && ($odataEntry instanceof ODataEntry))
         || (($resourceTypeKind == ResourceTypeKind::COMPLEX) && is_null($odataEntry))');
     $projectionNodes = null;
     $navigationProperties = null;
     if ($resourceTypeKind == ResourceTypeKind::ENTITY) {
         $projectionNodes = $this->getProjectionNodes();
         $navigationProperties = array();
     }
     if (is_null($projectionNodes)) {
         //This is the code path to handle properties of Complex type
         //or Entry without projection (i.e. no expansion or selection)
         $resourceProperties = array();
         if ($resourceTypeKind == ResourceTypeKind::ENTITY) {
             // If custom object is an entry then it can contain navigation
             // properties which are invisible (because the corrosponding
             // resource set is invisible).
             // IDSMP::getResourceProperties will give collection of properties
             // which are visible.
             $currentResourceSetWrapper1 = $this->getCurrentResourceSetWrapper();
             $resourceProperties = $this->dataService->getMetadataQueryProviderWrapper()->getResourceProperties($currentResourceSetWrapper1, $resourceType);
         } else {
             $resourceProperties = $resourceType->getAllProperties();
         }
         //First write out primitve types
         foreach ($resourceProperties as $name => $resourceProperty) {
             if ($resourceProperty->getKind() == ResourcePropertyKind::PRIMITIVE || $resourceProperty->getKind() == (ResourcePropertyKind::PRIMITIVE | ResourcePropertyKind::KEY) || $resourceProperty->getKind() == (ResourcePropertyKind::PRIMITIVE | ResourcePropertyKind::ETAG) || $resourceProperty->getKind() == (ResourcePropertyKind::PRIMITIVE | ResourcePropertyKind::KEY | ResourcePropertyKind::ETAG)) {
                 $odataProperty = new ODataProperty();
                 $primitiveValue = $this->getPropertyValue($customObject, $resourceType, $resourceProperty);
                 $this->_writePrimitiveValue($primitiveValue, $resourceProperty, $odataProperty);
                 $odataPropertyContent->odataProperty[] = $odataProperty;
             }
         }
         //Write out bag and complex type
         $i = 0;
         foreach ($resourceProperties as $resourceProperty) {
             if ($resourceProperty->isKindOf(ResourcePropertyKind::BAG)) {
                 //Handle Bag Property (Bag of Primitive or complex)
                 $propertyValue = $this->getPropertyValue($customObject, $resourceType, $resourceProperty);
                 $resourceType2 = $resourceProperty->getResourceType();
                 $this->_writeBagValue($propertyValue, $resourceProperty->getName(), $resourceType2, $relativeUri . '/' . $resourceProperty->getName(), $odataPropertyContent);
             } else {
                 $resourcePropertyKind = $resourceProperty->getKind();
                 if ($resourcePropertyKind == ResourcePropertyKind::COMPLEX_TYPE) {
                     $propertyValue = $this->getPropertyValue($customObject, $resourceType, $resourceProperty);
                     $resourceType1 = $resourceProperty->getResourceType();
                     $this->_writeComplexValue($propertyValue, $resourceProperty->getName(), $resourceType1, $relativeUri . '/' . $resourceProperty->getName(), $odataPropertyContent);
                 } else {
                     if ($resourceProperty->getKind() == ResourcePropertyKind::PRIMITIVE || $resourceProperty->getKind() == (ResourcePropertyKind::PRIMITIVE | ResourcePropertyKind::KEY) || $resourceProperty->getKind() == (ResourcePropertyKind::PRIMITIVE | ResourcePropertyKind::ETAG) || $resourceProperty->getKind() == (ResourcePropertyKind::PRIMITIVE | ResourcePropertyKind::KEY | ResourcePropertyKind::ETAG)) {
                         continue;
                     } else {
                         $this->assert($resourcePropertyKind == ResourcePropertyKind::RESOURCE_REFERENCE || $resourcePropertyKind == ResourcePropertyKind::RESOURCESET_REFERENCE, '($resourcePropertyKind == ResourcePropertyKind::RESOURCE_REFERENCE)
                          || ($resourcePropertyKind == ResourcePropertyKind::RESOURCESET_REFERENCE)');
                         $navigationProperties[$i] = new NavigationPropertyInfo($resourceProperty, $this->shouldExpandSegment($resourceProperty->getName()));
                         if ($navigationProperties[$i]->expanded) {
                             $navigationProperties[$i]->value = $this->getPropertyValue($customObject, $resourceType, $resourceProperty);
                         }
                         $i++;
                     }
                 }
             }
         }
     } else {
         //This is the code path to handle projected properties of Entry
         $i = 0;
         foreach ($projectionNodes as $projectionNode) {
             $propertyName = $projectionNode->getPropertyName();
             $resourceProperty = $resourceType->tryResolvePropertyTypeByName($propertyName);
             $this->assert(!is_null($resourceProperty), '!is_null($resourceProperty)');
             if ($resourceProperty->getTypeKind() == ResourceTypeKind::ENTITY) {
                 $currentResourceSetWrapper2 = $this->getCurrentResourceSetWrapper();
                 $resourceProperties = $this->dataService->getMetadataQueryProviderWrapper()->getResourceProperties($currentResourceSetWrapper2, $resourceType);
                 //Check for the visibility of this navigation property
                 if (array_key_exists($resourceProperty->getName(), $resourceProperties)) {
                     $navigationProperties[$i] = new NavigationPropertyInfo($resourceProperty, $this->shouldExpandSegment($propertyName));
                     if ($navigationProperties[$i]->expanded) {
                         $navigationProperties[$i]->value = $this->getPropertyValue($customObject, $resourceType, $resourceProperty);
                     }
                     $i++;
                     continue;
                 }
             }
             //Primitve, complex or bag property
             $propertyValue = $this->getPropertyValue($customObject, $resourceType, $resourceProperty);
             $propertyTypeKind = $resourceProperty->getKind();
             $propertyResourceType = $resourceProperty->getResourceType();
             $this->assert(!is_null($propertyResourceType), '!is_null($propertyResourceType)');
             if (ResourceProperty::sIsKindOf($propertyTypeKind, ResourcePropertyKind::BAG)) {
                 $bagResourceType = $resourceProperty->getResourceType();
                 $this->_writeBagValue($propertyValue, $propertyName, $bagResourceType, $relativeUri . '/' . $propertyName, $odataPropertyContent);
             } else {
                 if (ResourceProperty::sIsKindOf($propertyTypeKind, ResourcePropertyKind::PRIMITIVE)) {
                     $odataProperty = new ODataProperty();
                     $this->_writePrimitiveValue($propertyValue, $resourceProperty, $odataProperty);
                     $odataPropertyContent->odataProperty[] = $odataProperty;
                 } else {
                     if ($propertyTypeKind == ResourcePropertyKind::COMPLEX_TYPE) {
                         $complexResourceType = $resourceProperty->getResourceType();
                         $this->_writeComplexValue($propertyValue, $propertyName, $complexResourceType, $relativeUri . '/' . $propertyName, $odataPropertyContent);
                     } else {
                         //unexpected
                         $this->assert(false, '$propertyTypeKind = Primitive or Bag or ComplexType');
                     }
                 }
             }
         }
     }
     if (!is_null($navigationProperties)) {
         //Write out navigation properties (deferred or inline)
         foreach ($navigationProperties as $navigationPropertyInfo) {
             $propertyName = $navigationPropertyInfo->resourceProperty->getName();
             $type = $navigationPropertyInfo->resourceProperty->getKind() == ResourcePropertyKind::RESOURCE_REFERENCE ? 'application/atom+xml;type=entry' : 'application/atom+xml;type=feed';
             $link = new ODataLink();
             $link->name = ODataConstants::ODATA_RELATED_NAMESPACE . $propertyName;
             $link->title = $propertyName;
             $link->type = $type;
             $link->url = $relativeUri . '/' . $propertyName;
             if ($navigationPropertyInfo->expanded) {
                 $propertyRelativeUri = $relativeUri . '/' . $propertyName;
                 $propertyAbsoluteUri = trim($absoluteUri, '/') . '/' . $propertyName;
                 $needPop = $this->pushSegmentForNavigationProperty($navigationPropertyInfo->resourceProperty);
                 $navigationPropertyKind = $navigationPropertyInfo->resourceProperty->getKind();
                 $this->assert($navigationPropertyKind == ResourcePropertyKind::RESOURCESET_REFERENCE || $navigationPropertyKind == ResourcePropertyKind::RESOURCE_REFERENCE, '$navigationPropertyKind == ResourcePropertyKind::RESOURCESET_REFERENCE
                     || $navigationPropertyKind == ResourcePropertyKind::RESOURCE_REFERENCE');
                 $currentResourceSetWrapper = $this->getCurrentResourceSetWrapper();
                 $this->assert(!is_null($currentResourceSetWrapper), '!is_null($currentResourceSetWrapper)');
                 $link->isExpanded = true;
                 if (!is_null($navigationPropertyInfo->value)) {
                     if ($navigationPropertyKind == ResourcePropertyKind::RESOURCESET_REFERENCE) {
                         $inlineFeed = new ODataFeed();
                         $link->isCollection = true;
                         $currentResourceType = $currentResourceSetWrapper->getResourceType();
                         $this->_writeFeedElements($navigationPropertyInfo->value, $currentResourceType, $propertyName, $propertyAbsoluteUri, $propertyRelativeUri, $inlineFeed);
                         $link->expandedResult = $inlineFeed;
                     } else {
                         $inlineEntry = new ODataEntry();
                         $link->isCollection = false;
                         $currentResourceType1 = $currentResourceSetWrapper->getResourceType();
                         $this->_writeEntryElement($navigationPropertyInfo->value, $currentResourceType1, $propertyAbsoluteUri, $propertyRelativeUri, $inlineEntry);
                         $link->expandedResult = $inlineEntry;
                     }
                 } else {
                     $link->expandedResult = null;
                 }
                 $this->popSegment($needPop);
             }
             $odataEntry->links[] = $link;
         }
     }
 }
Example #24
0
 /**
  * Parse the given skiptoken, validate it using the given InternalOrderByInfo 
  * and generates instance of InternalSkipTokenInfo.
  * 
  * @param ResourceType        &$resourceType        The resource type of the
  *                                                  resource targetted by the
  *                                                  resource path.
  * @param InternalOrderByInfo &$internalOrderByInfo The $orderby details.
  * @param string              $skipToken            The $skiptoken value.
  * 
  * @return InternalSkipTokenInfo
  * 
  * @throws ODataException
  */
 public static function parseSkipTokenClause(ResourceType &$resourceType, InternalOrderByInfo &$internalOrderByInfo, $skipToken)
 {
     $tokenValueDescriptor = null;
     if (!KeyDescriptor::tryParseValuesFromSkipToken($skipToken, $tokenValueDescriptor)) {
         ODataException::createSyntaxError(Messages::skipTokenParserSyntaxError($skipToken));
     }
     $orderByPathSegments = null;
     //$positionalValues are of type array(int, array(string, IType))
     $positionalValues =& $tokenValueDescriptor->getPositionalValuesByRef();
     $count = count($positionalValues);
     $orderByPathSegments = $internalOrderByInfo->getOrderByPathSegments();
     $orderByPathCount = count($orderByPathSegments);
     if ($count != $orderByPathCount) {
         ODataException::createBadRequestError(Messages::skipTokenParserSkipTokenNotMatchingOrdering($count, $skipToken, $orderByPathCount));
     }
     $i = 0;
     foreach ($orderByPathSegments as $orderByPathSegment) {
         $typeProvidedInSkipToken = $positionalValues[$i][1];
         if (!$typeProvidedInSkipToken instanceof Null1) {
             $orderBySubPathSegments = $orderByPathSegment->getSubPathSegments();
             $j = count($orderBySubPathSegments) - 1;
             $expectedType = $orderBySubPathSegments[$j]->getInstanceType();
             if (!$expectedType->isCompatibleWith($typeProvidedInSkipToken)) {
                 ODataException::createSyntaxError(Messages::skipTokenParserInCompatibleTypeAtPosition($skipToken, $expectedType->getFullTypeName(), $i, $typeProvidedInSkipToken->getFullTypeName()));
             }
         }
         $i++;
     }
     return new InternalSkipTokenInfo($internalOrderByInfo, $positionalValues, $resourceType);
 }
 /**
  * Build nextpage link from the given object which will be the last object
  * in the page.
  * 
  * @param mixed $lastObject Entity instance to build next page link from.
  * 
  * @return string
  * 
  * @throws ODataException If reflection exception occurs while accessing 
  *                        property.
  */
 public function buildNextPageLink($lastObject)
 {
     $nextPageLink = null;
     foreach ($this->_internalOrderByInfo->getOrderByPathSegments() as $orderByPathSegment) {
         $index = 0;
         $currentObject = $lastObject;
         $subPathSegments = $orderByPathSegment->getSubPathSegments();
         $subPathCount = count($subPathSegments);
         foreach ($subPathSegments as &$subPathSegment) {
             $isLastSegment = $index == $subPathCount - 1;
             try {
                 $dummyProperty = new \ReflectionProperty($currentObject, $subPathSegment->getName());
                 $currentObject = $dummyProperty->getValue($currentObject);
                 if (is_null($currentObject)) {
                     $nextPageLink .= 'null, ';
                     break;
                 } else {
                     if ($isLastSegment) {
                         $type = $subPathSegment->getInstanceType();
                         $value = $type->convertToOData($currentObject);
                         $nextPageLink .= $value . ', ';
                     }
                 }
             } catch (\ReflectionException $reflectionException) {
                 throw ODataException::createInternalServerError(Messages::internalSkipTokenInfoFailedToAccessOrInitializeProperty($subPathSegment->getName()));
             }
             $index++;
         }
     }
     return rtrim($nextPageLink, ", ");
 }
Example #26
0
 /**
  * Execute the client submitted request aganist the data source.
  * 
  * @return void
  */
 public function execute()
 {
     $segmentDescriptors =& $this->_requestDescription->getSegmentDescriptors();
     foreach ($segmentDescriptors as $segmentDescriptor) {
         $requestTargetKind = $segmentDescriptor->getTargetKind();
         if ($segmentDescriptor->getTargetSource() == RequestTargetSource::ENTITY_SET) {
             $this->_handleSegmentTargetsToResourceSet($segmentDescriptor);
         } else {
             if ($requestTargetKind == RequestTargetKind::RESOURCE) {
                 if (is_null($segmentDescriptor->getPrevious()->getResult())) {
                     ODataException::createResourceNotFoundError($segmentDescriptor->getPrevious()->getIdentifier());
                 }
                 $this->_handleSegmentTargetsToRelatedResource($segmentDescriptor);
             } else {
                 if ($requestTargetKind == RequestTargetKind::LINK) {
                     $segmentDescriptor->setResult($segmentDescriptor->getPrevious()->getResult());
                 } else {
                     if ($segmentDescriptor->getIdentifier() == ODataConstants::URI_COUNT_SEGMENT) {
                         // we are done, $count will the last segment and
                         // taken care by _applyQueryOptions method
                         $segmentDescriptor->setResult($this->_requestDescription->getCountValue());
                         break;
                     } else {
                         if ($requestTargetKind == RequestTargetKind::MEDIA_RESOURCE) {
                             if (is_null($segmentDescriptor->getPrevious()->getResult())) {
                                 ODataException::createResourceNotFoundError($segmentDescriptor->getPrevious()->getIdentifier());
                             }
                             // For MLE and Named Stream the result of last segment
                             // should be that of previous segment, this is required
                             // while retriving content type or stream from IDSSP
                             $segmentDescriptor->setResult($segmentDescriptor->getPrevious()->getResult());
                             // we are done, as named stream property or $value on
                             // media resource will be the last segment
                             break;
                         } else {
                             $value = $segmentDescriptor->getPrevious()->getResult();
                             while (!is_null($segmentDescriptor)) {
                                 if (is_null($value)) {
                                     $value = null;
                                 } else {
                                     try {
                                         $property = new \ReflectionProperty($value, $segmentDescriptor->getIdentifier());
                                         $value = $property->getValue($value);
                                     } catch (\ReflectionException $reflectionException) {
                                         //throw ODataException::createInternalServerError(Messages::orderByParserFailedToAccessOrInitializeProperty($resourceProperty->getName(), $resourceType->getName()));
                                     }
                                 }
                                 $segmentDescriptor->setResult($value);
                                 $segmentDescriptor = $segmentDescriptor->getNext();
                                 if (!is_null($segmentDescriptor) && $segmentDescriptor->getIdentifier() == ODataConstants::URI_VALUE_SEGMENT) {
                                     $segmentDescriptor->setResult($value);
                                     $segmentDescriptor = $segmentDescriptor->getNext();
                                 }
                             }
                             //done, exit from outer loop as inner while complete traversal.
                             break;
                         }
                     }
                 }
             }
         }
         if (is_null($segmentDescriptor->getNext()) || $segmentDescriptor->getNext()->getIdentifier() == ODataConstants::URI_COUNT_SEGMENT) {
             $this->_applyQueryOptions($segmentDescriptor);
         }
     }
     // Apply $select and $expand options to result set, this function will be always applied
     // irrespective of return value of IDSQP2::canApplyQueryOptions which means library will
     // not delegate $expand/$select operation to IDSQP2 implementation
     $this->_handleExpansion();
 }
 /**
  * Get related resource for a resource
  * 
  * @param ResourceSet      $sourceResourceSet    The source resource set
  * @param mixed            $sourceEntityInstance The source resource
  * @param ResourceSet      $targetResourceSet    The resource set of 
  *                                               the navigation property
  * @param ResourceProperty $targetProperty       The navigation property to be 
  *                                               retrieved
  * 
  * @return Object/null The related resource if exists else null
  */
 public function getRelatedResourceReference(ResourceSet $sourceResourceSet, $sourceEntityInstance, ResourceSet $targetResourceSet, ResourceProperty $targetProperty)
 {
     $result = null;
     $srcClass = get_class($sourceEntityInstance);
     $navigationPropName = $targetProperty->getName();
     if ($srcClass === 'Order') {
         if ($navigationPropName === 'Customer') {
             if (empty($sourceEntityInstance->CustomerID)) {
                 $result = null;
             } else {
                 $query = "SELECT * FROM Customers WHERE CustomerID = '{$sourceEntityInstance->CustomerID}'";
                 $stmt = sqlsrv_query($this->_connectionHandle, $query);
                 if ($stmt === false) {
                     $errorAsString = self::_getSQLSRVError();
                     ODataException::createInternalServerError($errorAsString);
                 }
                 if (!sqlsrv_has_rows($stmt)) {
                     $result = null;
                 }
                 $result = $this->_serializeCustomer(sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC));
             }
         } else {
             ODataException::createInternalServerError('Customer does not have navigation porperty with name: ' . $navigationPropName . ' Contact Service Provider');
         }
     } else {
         if ($srcClass === 'Order_Details') {
             if ($navigationPropName === 'Order') {
                 if (empty($sourceEntityInstance->OrderID)) {
                     $result = null;
                 } else {
                     $query = "SELECT * FROM Orders WHERE OrderID = {$sourceEntityInstance->OrderID}";
                     $stmt = sqlsrv_query($this->_connectionHandle, $query);
                     if ($stmt === false) {
                         $errorAsString = self::_getSQLSRVError();
                         ODataException::createInternalServerError($errorAsString);
                     }
                     if (!sqlsrv_has_rows($stmt)) {
                         $result = null;
                     }
                     $result = $this->_serializeOrder(sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC));
                 }
             } else {
                 ODataException::createInternalServerError('Order_Details does not have navigation porperty with name: ' . $navigationPropName . ' Contact Service Provider');
             }
         }
     }
     return $result;
 }
Example #28
0
 /**
  * Assert that the given condition is true, if false throw 
  * ODataException for syntax error
  * 
  * @param boolean $condition The condition to assert
  * 
  * @return void
  * 
  * @throws ODataException
  */
 private function _assertion($condition)
 {
     if (!$condition) {
         ODataException::createSyntaxError(Messages::syntaxError());
     }
 }
Example #29
0
 /**
  * To check whether the the query options $select, $expand
  * is applicable for the current requested resource.
  * 
  * @param string $queryItem The query option to check.
  * 
  * @return void
  * 
  * @throws ODataException Throws bad request error if the query 
  *                        options $select, $expand cannot be 
  *                        applied to the requested resource. 
  */
 private function _checkExpandOrSelectApplicable($queryItem)
 {
     if (!$this->_expandSelectApplicable) {
         ODataException::createBadRequestError(Messages::queryProcessorSelectOrExpandOptionNotApplicable($queryItem));
     }
 }
 /**
  * Ask data service to load stream provider instance.
  * 
  * @return void
  * 
  * @throws ODataException
  */
 private function _loadStreamProvider()
 {
     if (is_null($this->_streamProvider)) {
         $maxServiceVersion = $this->_dataService->getServiceConfiguration()->getMaxDataServiceVersionObject();
         if ($maxServiceVersion->compare(new Version(3, 0)) >= 0) {
             $this->_streamProvider = $this->_dataService->getService('IDataServiceStreamProvider2');
             if (!is_null($this->_streamProvider) && (!is_object($this->_streamProvider) || array_search('ODataProducer\\Providers\\Stream\\IDataServiceStreamProvider2', class_implements($this->_streamProvider)) === false)) {
                 ODataException::createInternalServerError(Messages::dataServiceStreamProviderWrapperInvalidStream2Instance());
             }
         }
         if (is_null($this->_streamProvider)) {
             $this->_streamProvider = $this->_dataService->getService('IDataServiceStreamProvider');
             if (!is_null($this->_streamProvider) && (!is_object($this->_streamProvider) || array_search('ODataProducer\\Providers\\Stream\\IDataServiceStreamProvider', class_implements($this->_streamProvider)) === false)) {
                 ODataException::createInternalServerError(Messages::dataServiceStreamProviderWrapperInvalidStreamInstance());
             }
         }
     }
 }