Skip to content

Instantly share code, notes, and snippets.

@Tocacar
Created January 17, 2014 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tocacar/8471930 to your computer and use it in GitHub Desktop.
Save Tocacar/8471930 to your computer and use it in GitHub Desktop.
//CMMIDataHelper.php
/**
* @param \RecursiveArrayIterator $iterator
* @return mixed
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
protected function buildResources(\RecursiveArrayIterator $iterator)
{
if(count($this->mapping) == 0) {
throw new HttpException(Codes::HTTP_BAD_REQUEST, 'Unable to generate CMMI Data, no mapping is known');
}
$this->resource = new Resource(new Link($this->request->getUri(), 'self'));
if($iterator->hasChildren()) {
while($iterator->valid()) {
$childItem = $iterator->current();
$this->addResource($childItem);
$iterator->next();
}
} else {
$this->addResource($iterator);
}
return $this->resource;
}
/**
* @param $item
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
* @return void
*/
protected function addResource($item)
{
if(!$item->getSlug()) {
throw new HttpException(Codes::HTTP_BAD_REQUEST, 'Cannot add resource, identifier not known in the iterator');
}
$mediaResource = new Resource(new Link('/' . $this->route . '/' . $item->getSlug(), 'self'), $this->route);
// Add the mapping to the resource
$this->mapResource($mediaResource, $item);
$this->resource->addResource($mediaResource);
}
/**
* Map all the fields into the resource
*
* @param Resource $resource
* @param \RecursiveArrayIterator $item
*/
protected function mapResource(Resource $resource, $item)
{
// Map all the fields in the resource
foreach($this->mapping as $mappingKey => $mappingValue)
{
$getter = 'get'.ucfirst($mappingValue);
if(!$item->$getter()) {
throw new HttpException('Cannot map resource, key "' . $mappingValue . '" not known in the iterator', Codes::HTTP_BAD_REQUEST);
}
$resource->$mappingKey = $item->$getter();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment