/**
  * @param mixed $resource
  * @param null|string|array $includes
  * @return array
  */
 private function convertResource($resource, $includes = null)
 {
     if ($includes !== null) {
         $this->manager->parseIncludes($includes);
     }
     return $this->manager->createData($resource)->toArray();
 }
 /**
  * Include the selected relationships in the Fractal Transformer
  *
  * @param  string
  * @return $this
  */
 public function includeRelated($includes)
 {
     if ($includes != null) {
         $this->fractal->parseIncludes($includes);
     }
     return $this;
 }
 /**
  * includes sub level data transformer.
  * @param array $includes
  * @return $this
  */
 public function includes(array $includes)
 {
     // when autoload is enable, we need to merge user requested includes with the predefined includes.
     if ($this->autoload and $this->request->get($this->input_key)) {
         $includes = array_merge($includes, explode(',', $this->request->get($this->input_key)));
     }
     $this->manager->parseIncludes($includes);
     return $this;
 }
示例#4
0
 /**
  * @return $this
  */
 protected function parseIncludes()
 {
     $request = app('Illuminate\\Http\\Request');
     $paramIncludes = config('warehouse.fractal.params.include', 'include');
     if ($request->has($paramIncludes)) {
         $this->fractal->parseIncludes($request->get($paramIncludes));
     }
     return $this;
 }
 /**
  * @return $this
  */
 protected function parseIncludes()
 {
     $request = $this->application->make('Illuminate\\Http\\Request');
     $paramIncludes = Config::get('reloquent.fractal.params.include', 'include');
     if ($request->has($paramIncludes)) {
         $this->fractal->parseIncludes($request->get($paramIncludes));
     }
     return $this;
 }
示例#6
0
 function __construct(Manager $fractal)
 {
     // Need to do Authentication HERE!
     $this->beforeFilter('auth');
     // Check if the request is from allowable hosts
     $this->checkAllowables();
     $this->fractal = $fractal;
     if (Request::has('include')) {
         $this->fractal->parseIncludes(Request::get('include'));
     }
 }
 /**
  * Constructor.
  *
  * @param Request $request
  */
 public function __construct(Request $request)
 {
     $this->model = $this->model();
     $this->transformer = $this->transformer();
     $this->fractal = new Manager();
     $this->request = $request;
     $this->fractal->setSerializer($this->serializer());
     if ($this->request->has('include')) {
         $this->fractal->parseIncludes(camel_case($this->request->input('include')));
     }
 }
 public function testRecursionLimiting()
 {
     $manager = new Manager();
     // Should limit to 10 by default
     $manager->parseIncludes('a.b.c.d.e.f.g.h.i.j.NEVER');
     $this->assertEquals(array('a', 'a.b', 'a.b.c', 'a.b.c.d', 'a.b.c.d.e', 'a.b.c.d.e.f', 'a.b.c.d.e.f.g', 'a.b.c.d.e.f.g.h', 'a.b.c.d.e.f.g.h.i', 'a.b.c.d.e.f.g.h.i.j'), $manager->getRequestedIncludes());
     // Try setting to 3 and see what happens
     $manager->setRecursionLimit(3);
     $manager->parseIncludes('a.b.c.NEVER');
     $this->assertEquals(array('a', 'a.b', 'a.b.c'), $manager->getRequestedIncludes());
 }
示例#9
0
 /**
  * Handle domain logic for an action.
  *
  * @param  array $input
  * @return PayloadInterface
  */
 public function __invoke(array $input)
 {
     //Authorize user to be able to view shifts
     $this->authorizeUser($input[AuthHandler::TOKEN_ATTRIBUTE]->getMetaData('entity'), 'view', 'shifts');
     //Validate input
     $inputValidator = v::key('startDateTime', v::stringType())->key('endDateTime', v::stringType());
     $inputValidator->assert($input);
     //Retrieve shifts between in time period
     $shifts = $this->shiftRepository->getShiftsBetween(Carbon::parse($input['startDateTime']), Carbon::parse($input['endDateTime']));
     $this->collection->setData($shifts)->setTransformer($this->shiftTransformer);
     return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->parseIncludes(['manager', 'employee'])->createData($this->collection)->toArray());
 }
 /**
  * Create Ember Data friendly response
  *
  * @param $data
  * @param $model
  * @param array $includes
  * @return array
  * @throws Exceptions\SerializerTranslatorException
  */
 public function make($data, $model, $includes = [])
 {
     if (!$data || empty($data)) {
         return [];
     }
     $transformer = app($this->translator->toTranslatorHandler($model));
     $resource = $this->createResource($data, $transformer, $model);
     if (!empty($includes)) {
         $this->manager->parseIncludes($includes);
     }
     return $this->manager->createData($resource)->toArray();
 }
示例#11
0
 /**
  * Handle domain logic for an action.
  *
  * @param  array $input
  * @return PayloadInterface
  */
 public function __invoke(array $input)
 {
     //Check that user has permission to edit this resource
     $this->authorizeUser($input[AuthHandler::TOKEN_ATTRIBUTE]->getMetaData('entity'), 'edit', 'shifts');
     //Validate input
     $inputValidator = v::key('id', v::intVal())->key('employee_id', v::intVal());
     $inputValidator->assert($input);
     //Execute command to update employee on shift
     $shift = $this->commandBus->handle(new AssignShiftCommand($input['id'], $input['employee_id']));
     $shiftItem = new Item($shift, new ShiftTransformer());
     return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->parseIncludes(['manager', 'employee'])->createData($shiftItem)->toArray());
 }
示例#12
0
 /** @test */
 public function it_should_transform_item_with_includes()
 {
     $this->manager->parseIncludes('workplace');
     $userWorkplace = new UserWorkplaceEntityStub();
     $userWorkplace->setName('Doe\'s Constructions');
     $user = new UserEntityStub();
     $user->setName('John Doe');
     $user->setEmail('*****@*****.**');
     $user->setWorkplace($userWorkplace);
     $scope = $this->transformer->transformItem($user);
     $this->assertInstanceOf(\League\Fractal\Scope::class, $scope);
     $this->assertEquals(['data' => ['name' => 'John Doe', 'email' => '*****@*****.**', 'workplace' => ['data' => ['name' => 'Doe\'s Constructions']]]], $scope->toArray());
 }
 /**
  * Register the service provider.
  *
  * @return void
  */
 public function register()
 {
     if ($this->isLumen()) {
         require_once 'fallback.php';
     }
     $this->registerRequiredProviders();
     $this->app->bind('datatables.html', function () {
         return $this->app->make(Html\Builder::class);
     });
     $this->app->singleton('datatables.fractal', function () {
         $fractal = new Manager();
         $config = $this->app['config'];
         $request = $this->app['request'];
         $includesKey = $config->get('datatables.fractal.includes', 'include');
         if ($request->get($includesKey)) {
             $fractal->parseIncludes($request->get($includesKey));
         }
         $serializer = $config->get('datatables.fractal.serializer', DataArraySerializer::class);
         $fractal->setSerializer(new $serializer());
         return $fractal;
     });
     $this->app->singleton('datatables', function () {
         return new Datatables($this->app->make(Request::class));
     });
     $this->registerAliases();
 }
示例#14
0
 public function index(Request $request, Manager $fractal)
 {
     if ($requestedEmbeds = $request->get('include')) {
         $fractal->parseIncludes($requestedEmbeds);
     }
     return $this->response->item($this->user, UserTransformer::class);
 }
示例#15
0
 /**
  * @param Manager $fractal
  */
 public function __construct(Manager $fractal)
 {
     $this->fractal = $fractal;
     if (isset($_GET['include'])) {
         $fractal->parseIncludes($_GET['include']);
     }
 }
示例#16
0
 /**
  * @param $resource
  * @return mixed
  */
 public function responseWithTransformer($resource, $code)
 {
     $manager = new Manager();
     $manager->setSerializer(new DataArraySerializer());
     $manager->parseIncludes(request()->get('includes', []));
     return response()->json($manager->createData($resource)->toArray(), $code);
 }
 public function __construct(Manager $fractal)
 {
     $this->fractal = $fractal;
     if (Input::get('include')) {
         $fractal->parseIncludes(Input::get('include'));
     }
 }
示例#18
0
 public function createResponseArray($data, $entity, Request $request)
 {
     $this->request = $request;
     $fractal = new Manager();
     $fractal->parseIncludes($request->query->get('include', []));
     $fractal->setSerializer(new ArraySerializer());
     $transformer = $this->transformerFactory->get($entity);
     if ($data instanceof Pagerfanta) {
         $pager = $data;
         $pager->setMaxPerPage($request->query->get('limit', 10));
         $pager->setCurrentPage($request->query->get('page', 1));
         $results = $pager->getCurrentPageResults();
         $resource = new Collection($results, $transformer);
         $resource->setPaginator(new PagerfantaPaginatorAdapter($pager, [$this, 'paginationRouter']));
     } elseif ($data instanceof DoctrineQuery) {
         $ormAdapter = new DoctrineORMAdapter($data);
         $pager = new Pagerfanta($ormAdapter);
         $pager->setMaxPerPage($request->query->get('limit', 10));
         $pager->setCurrentPage($request->query->get('page', 1));
         $results = $pager->getCurrentPageResults();
         $resource = new Collection($results, $transformer);
         $resource->setPaginator(new PagerfantaPaginatorAdapter($pager, [$this, 'paginationRouter']));
     } elseif (is_array($data)) {
         $resource = new Collection($data, $transformer);
     } else {
         $resource = new Item($data, $transformer);
     }
     $data = $fractal->createData($resource)->toArray();
     return $data;
 }
示例#19
0
/**
 * @VP:
 * I'm trying to pass a second parameter to my transformer but don't know how.
 * @param $resource
 */
function transform($resource)
{
    $manager = new Manager();
    $manager->setSerializer(new DataArraySerializer());
    $manager->parseIncludes(request()->get('includes', []));
    return $manager->createData($resource)->toArray();
}
 /**
  * Include Content
  *
  * @param BaseElementModel $element Element
  *
  * @return League\Fractal\Resource\Item Content
  */
 public function includeContent(BaseElementModel $element)
 {
     $content = [];
     if ($this->depth > \Craft\craft()->config->get('contentRecursionLimit', 'httpMessagesRestMiddleware') - 1) {
         return;
     }
     foreach ($element->getFieldLayout()->getFields() as $fieldLayoutField) {
         $field = $fieldLayoutField->getField();
         $value = $element->getFieldValue($field->handle);
         if (get_class($field->getFieldType()) === 'Craft\\RichTextFieldType') {
             $value = $value->getRawContent();
         }
         if (is_object($value) && get_class($value) === 'Craft\\ElementCriteriaModel') {
             $class = get_class($value->getElementType());
             $element_type = $this->element_service->getElementTypeByClass($class);
             $manager = new Manager();
             $manager->parseIncludes(array_merge(['content'], explode(',', \Craft\craft()->request->getParam('include'))));
             $manager->setSerializer(new ArraySerializer());
             $transformer = $this->config_service->getTransformer($element_type);
             $value = $value->find();
             $body = new Collection($value, new $transformer($this->depth + 1));
             $value = $manager->createData($body)->toArray();
             $value = !empty($value['data']) ? $value['data'] : null;
         }
         $content[$field->handle] = $value;
     }
     if ($content) {
         return $this->item($content, new ContentTransformer($this->depth), 'content');
     }
 }
 /**
  * Register the service provider.
  *
  * @return void
  */
 public function register()
 {
     $source_config = __DIR__ . '/../../config/fractal.php';
     $this->mergeConfigFrom($source_config, 'fractal');
     $this->app->singleton('fractal', function ($app) {
         // retrieves configurations
         $autoload = $app['config']->get('fractal.autoload');
         $input_key = $app['config']->get('fractal.input_key');
         $exclude_key = $app['config']->get('fractal.exclude_key');
         $serializer = $app['config']->get('fractal.serializer');
         // creating fractal manager instance
         $manager = new Manager();
         $factalNamespace = 'League\\Fractal\\Serializer\\';
         $loadSerializer = class_exists($factalNamespace . $serializer) ? $factalNamespace . $serializer : $serializer;
         $manager->setSerializer(new $loadSerializer());
         if ($autoload === true and $includes = $app['request']->input($input_key)) {
             $manager->parseIncludes($includes);
         }
         if ($app['request']->has($exclude_key)) {
             $manager->parseExcludes($app['request']->input($exclude_key));
         }
         return new FractalServices($manager, $app['app']);
     });
     $this->app->alias('fractal', FractalServices::class);
     // register our command here
     $this->app['command.transformer.generate'] = $this->app->share(function ($app) {
         return new TransformerGeneratorCommand($app['config'], $app['view'], $app['files'], $app);
     });
     $this->commands('command.transformer.generate');
 }
示例#22
0
文件: Fractal.php 项目: jieke360/api
 /**
  * Parse the includes.
  *
  * @param \Dingo\Api\Http\Request $request
  *
  * @return void
  */
 public function parseFractalIncludes(Request $request)
 {
     $includes = $request->get($this->includeKey);
     if (!is_array($includes)) {
         $includes = array_filter(explode($this->includeSeparator, $includes));
     }
     $this->fractal->parseIncludes($includes);
 }
 /**
  * Handle domain logic for an action.
  *
  * @param  array $input
  * @return PayloadInterface
  * @throws UserNotAuthorized
  */
 public function __invoke(array $input)
 {
     //Check that the auth user matches the requested user
     //todo: determine if manager's should have access
     if ($input[AuthHandler::TOKEN_ATTRIBUTE]->getMetadata('id') != $input['id']) {
         throw new UserNotAuthorized();
     }
     $employee = $this->userRepository->getOneByIdOrFail($input['id']);
     $shifts = $this->shiftRepository->getByEmployee($employee);
     //Loop over shifts getting employees that work at the same time for each shift
     foreach ($shifts as $shift) {
         $coworkers = $this->userRepository->getEmployeesWorkingBetween($shift->getStartTime(), $shift->getEndTime(), [$employee]);
         $shift->setCoworkers($coworkers);
     }
     $this->collection->setData($shifts)->setTransformer($this->shiftTransformer);
     return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->parseIncludes('coworkers')->createData($this->collection)->toArray());
 }
示例#24
0
 /**
  * Constructor
  */
 public function __construct()
 {
     $this->response = \Response::api();
     if (!empty($this->modelName)) {
         $this->model = new $this->modelName();
     }
     // if no collection name provided, use the model's table name
     if (empty($this->collectionName)) {
         $this->collectionName = $this->model->getTable();
     }
     // parse includes
     if (\Input::get('include') != '') {
         $this->manager = new \League\Fractal\Manager();
         $this->manager->parseIncludes(explode(',', \Input::get('include')));
     }
     parent::__construct();
 }
 public function booksAllWithTransformer()
 {
     $fractal = new Manager();
     $fractal->parseIncludes('author');
     $books = Book::all();
     $resource = new Collection($books, new BookTransformer());
     return $fractal->createData($resource)->toJson();
 }
示例#26
0
 /**
  * @param Manager $fractal
  */
 public function __construct(Manager $fractal)
 {
     $this->fractal = $fractal;
     $this->fractal->setRequestedScopes(explode(',', Input::get('embed')));
     if (isset($_GET['include'])) {
         $fractal->parseIncludes($_GET['include']);
     }
 }
示例#27
0
 /**
  * Handle domain logic for an action.
  *
  * @param array $input
  * @return PayloadInterface
  */
 public function __invoke(array $input)
 {
     //Ensure that the use has permission to create shifts
     $user = $input[AuthHandler::TOKEN_ATTRIBUTE]->getMetadata('entity');
     $this->authorizeUser($user, 'create', 'shifts');
     //If no manager_id is specified in request, default to user creating shift
     if (!array_key_exists('manager_id', $input)) {
         $input['manager_id'] = $user->getId();
     }
     //Validate input
     $inputValidator = v::key('break', v::floatVal())->key('start_time', v::date())->key('end_time', v::date()->min($input['start_time']))->key('manager_id', v::intVal());
     $inputValidator->assert($input);
     //Execute command to create shift
     $shift = $this->commandBus->handle(new CreateShift($input['manager_id'], $input['employee_id'], $input['break'], $input['start_time'], $input['end_time']));
     $this->item->setData($shift)->setTransformer($this->shiftTransformer);
     return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->parseIncludes(['manager', 'employee'])->createData($this->item)->toArray());
 }
示例#28
0
 /**
  * @param array $input
  * @return PayloadInterface
  * @throws UserNotAuthorized
  */
 public function __invoke(array $input)
 {
     //Don't allow employees to view other employee's shifts
     //todo: figure out if managers can access all employees' shifts
     if ($input['id'] != $input[AuthHandler::TOKEN_ATTRIBUTE]->getMetaData('id')) {
         throw new UserNotAuthorized();
     }
     //Validate input
     $inputValidator = v::key('id', v::intVal());
     $inputValidator->assert($input);
     //Get shifts and transform
     $employee = $this->userRepository->getOneByIdOrFail($input['id']);
     $shifts = $this->shiftRepository->getByEmployee($employee);
     $this->collection->setData($shifts)->setTransformer($this->shiftTransformer);
     $include = array_key_exists('include', $input) ? $input['include'] : '';
     return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->parseIncludes($include)->createData($this->collection)->toArray());
 }
示例#29
0
 /**
  * @param object[] $objects All instances are expected to be of the same class.
  * @param Context  $context
  *
  * @return array
  */
 public function normalizeObjectCollection(array $objects, Context $context)
 {
     if (count($objects) === 0) {
         return [];
     }
     $class = ClassUtils::getClass(reset($object));
     foreach ($objects as $object) {
         if (!is_object($object)) {
             throw new \InvalidArgumentException(sprintf('All arguments are expected to be instances of objects, "%s" found.', gettype($object)));
         }
         if (!$object instanceof $class) {
             throw new \InvalidArgumentException(sprintf('All objects are expected to be an instance of "%s", an instance of "%s" found.', $class, ClassUtils::getClass($object)));
         }
     }
     // "Includes" are stateful, so make sure they are always explicitly set.
     $this->manager->parseIncludes($context->getIncludesAsString());
     return $this->manager->createData(new Collection($objects, $this->transformerRegistry->get($class)))->toArray();
 }
 /**
  * Get the Fractal resource instance.
  *
  * @return \League\Fractal\Resource\ResourceInterface
  */
 public function getResource() : ResourceInterface
 {
     $this->manager->parseIncludes($this->relations);
     $transformer = $this->resource->getTransformer();
     if ($transformer instanceof Transformer && $transformer->allRelationsAllowed()) {
         $this->resource->setTransformer($transformer->setRelations($this->manager->getRequestedIncludes()));
     }
     return $this->resource->setMeta($this->meta);
 }