コード例 #1
0
 /**
  * @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();
 }
コード例 #2
0
 /**
  * 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;
 }
コード例 #3
0
 /**
  * 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;
 }
コード例 #5
0
 /**
  * @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
ファイル: ApiController.php プロジェクト: ratiw/api
 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'));
     }
 }
コード例 #7
0
 /**
  * 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')));
     }
 }
コード例 #8
0
 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());
 }
コード例 #10
0
 /**
  * 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());
 }
コード例 #13
0
 /**
  * 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
ファイル: Controller.php プロジェクト: JennySwift/dental
 /**
  * @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);
 }
コード例 #17
0
 public function __construct(Manager $fractal)
 {
     $this->fractal = $fractal;
     if (Input::get('include')) {
         $fractal->parseIncludes(Input::get('include'));
     }
 }
コード例 #18
0
ファイル: RestResponse.php プロジェクト: cvele/fondacija
 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
ファイル: helpers.php プロジェクト: JennySwift/health-tracker
/**
 * @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();
}
コード例 #20
0
 /**
  * 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');
     }
 }
コード例 #21
0
 /**
  * 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);
 }
コード例 #23
0
 /**
  * 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();
 }
コード例 #25
0
 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
ファイル: ApiController.php プロジェクト: justem007/rossina
 /**
  * @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
ファイル: Normalizer.php プロジェクト: Briareos/Undine
 /**
  * @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();
 }
コード例 #30
0
 /**
  * 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);
 }