├── src ├── views │ ├── .gitkeep │ └── transformer.php ├── config │ ├── .gitkeep │ └── fractal.php ├── migrations │ └── .gitkeep └── Cyvelnet │ └── Laravel5Fractal │ ├── Facades │ └── Fractal.php │ ├── Adapters │ ├── ScopeDataAdapterInterface.php │ └── ScopeDataAdapter.php │ ├── Serializers │ └── ExtendedArraySerializer.php │ ├── Paginators │ └── IlluminateLengthAwarePaginatorAdapter.php │ ├── Laravel5FractalServiceProvider.php │ ├── Commands │ ├── TransformerGeneratorCommand.php │ └── Command.php │ ├── Traits │ └── Transformable.php │ └── FractalServices.php ├── phpunit.xml ├── LICENSE ├── composer.json └── README.md /src/views/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/config/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/migrations/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/Cyvelnet/Laravel5Fractal/Facades/Fractal.php: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 15 | ./tests/ 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/Cyvelnet/Laravel5Fractal/Adapters/ScopeDataAdapterInterface.php: -------------------------------------------------------------------------------- 1 | 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cyvelnet/laravel5-fractal", 3 | "description": "A simple fractal service provider and transformer generator with model attributes for laravel >=5.", 4 | "keywords": ["laravel","fractal","api","transformer"], 5 | "license": "MIT", 6 | "authors": [ 7 | { 8 | "name": "Cyvelnet", 9 | "email": "cyvelnet@gmail.com" 10 | } 11 | ], 12 | "require": { 13 | "php": "^5.6|^7.0|^8.0", 14 | "illuminate/support": "^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.0 ||^10.0 || ^11.0", 15 | "league/fractal" :"0.20.*", 16 | "doctrine/dbal": "^2.5" 17 | }, 18 | "require-dev": { 19 | "orchestra/testbench": "~3.2.0|~3.3.0|~3.4.0", 20 | "phpunit/phpunit" : "^5.7" 21 | }, 22 | "autoload": { 23 | "classmap": [ 24 | "src/migrations" 25 | ], 26 | "psr-0": { 27 | "Cyvelnet\\Laravel5Fractal\\": "src/" 28 | } 29 | }, 30 | "autoload-dev": { 31 | "files": [ 32 | "tests/TestCase.php" 33 | ] 34 | }, 35 | "extra":{ 36 | "laravel":{ 37 | "providers":[ 38 | "Cyvelnet\\Laravel5Fractal\\Laravel5FractalServiceProvider" 39 | ], 40 | "aliases":{ 41 | "Fractal":"Cyvelnet\\Laravel5Fractal\\Facades\\Fractal" 42 | } 43 | } 44 | }, 45 | "minimum-stability": "stable" 46 | } 47 | -------------------------------------------------------------------------------- /src/views/transformer.php: -------------------------------------------------------------------------------- 1 | 4 | 5 | 10 | 11 | 12 | 13 | 14 | 17 | 18 | /** 19 | * List of resources possible to include 20 | * 21 | * @var array 22 | */ 23 | protected $availableIncludes = []; 24 | 25 | /** 26 | * List of resources to automatically include 27 | * 28 | * @var array 29 | */ 30 | protected $defaultIncludes = []; 31 | 32 | /** 33 | * Transform object into a generic array 34 | * 35 | * @var 36 | * @return array 37 | */ 38 | public function transform() 39 | { 40 | return [ 41 | 42 | ({$attribute['casts']}) \$resource->{$attribute['column']},\r\n\t\t\t"; 46 | } else { 47 | echo "'{$attribute['column']}' => \$resource->{$attribute['column']},\r\n\t\t\t"; 48 | } 49 | } 50 | 51 | ?> 52 | 53 | ]; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/Cyvelnet/Laravel5Fractal/Adapters/ScopeDataAdapter.php: -------------------------------------------------------------------------------- 1 | scope = $scope; 25 | } 26 | 27 | /** 28 | * generate a json response. 29 | * 30 | * @param int $http_status 31 | * @param array $header 32 | * 33 | * @return ResponseFactory|\Symfony\Component\HttpFoundation\Response 34 | */ 35 | public function responseJson($http_status = 200, $header = []) 36 | { 37 | return response($this->getArray(), $http_status, $header); 38 | } 39 | 40 | /** 41 | * get the transformed array data. 42 | * 43 | * @return array 44 | */ 45 | public function getArray() 46 | { 47 | return $this->scope->toArray(); 48 | } 49 | 50 | /** 51 | * get the transformed json data. 52 | * 53 | * @param int $options 54 | * 55 | * @return string 56 | */ 57 | public function getJson($options = 0) 58 | { 59 | return $this->scope->toJson($options); 60 | } 61 | 62 | /** 63 | * get the transformed json data. 64 | * 65 | * @param int $options 66 | * 67 | * @return string 68 | */ 69 | public function toJson($options = 0) 70 | { 71 | return $this->scope->toJson($options); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/Cyvelnet/Laravel5Fractal/Serializers/ExtendedArraySerializer.php: -------------------------------------------------------------------------------- 1 | getCurrentPage(); 23 | $lastPage = (int) $paginator->getLastPage(); 24 | 25 | $pagination = [ 26 | 'total' => (int) $paginator->getTotal(), 27 | 'count' => (int) $paginator->getCount(), 28 | 'per_page' => (int) $paginator->getPerPage(), 29 | 'current_page' => $currentPage, 30 | 'total_pages' => $lastPage, 31 | ]; 32 | 33 | $pagination['links'] = []; 34 | 35 | if ($currentPage !== 1) { 36 | $pagination['links']['first'] = $paginator->getUrl(1); 37 | } 38 | 39 | if ($currentPage > 1) { 40 | $pagination['links']['previous'] = $paginator->getUrl($currentPage - 1); 41 | } 42 | 43 | // add fast backward 44 | if (($fastBack = ($currentPage - 10)) >= 1) { 45 | $pagination['links']['fastback'] = $paginator->getUrl($fastBack); 46 | } 47 | 48 | if ($currentPage < $lastPage) { 49 | $pagination['links']['next'] = $paginator->getUrl($currentPage + 1); 50 | } 51 | 52 | // add fast backward 53 | if (($fastForward = ($currentPage + 10)) <= $lastPage) { 54 | $pagination['links']['fastforward'] = $paginator->getUrl($fastForward); 55 | } 56 | 57 | if ($lastPage > 1 && $currentPage !== $lastPage) { 58 | $pagination['links']['last'] = $paginator->getUrl($lastPage); 59 | } 60 | 61 | return ['pagination' => $pagination]; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/Cyvelnet/Laravel5Fractal/Paginators/IlluminateLengthAwarePaginatorAdapter.php: -------------------------------------------------------------------------------- 1 | paginator = $paginator; 28 | } 29 | 30 | /** 31 | * Get the current page. 32 | * 33 | * @return int 34 | */ 35 | public function getCurrentPage() 36 | { 37 | return $this->paginator->currentPage(); 38 | } 39 | 40 | /** 41 | * Get the last page. 42 | * 43 | * @return int 44 | */ 45 | public function getLastPage() 46 | { 47 | return $this->paginator->LastPage(); 48 | } 49 | 50 | /** 51 | * Get the total. 52 | * 53 | * @return int 54 | */ 55 | public function getTotal() 56 | { 57 | return $this->paginator->Total(); 58 | } 59 | 60 | /** 61 | * Get the count. 62 | * 63 | * @return int 64 | */ 65 | public function getCount() 66 | { 67 | return $this->paginator->count(); 68 | } 69 | 70 | /** 71 | * Get the number per page. 72 | * 73 | * @return int 74 | */ 75 | public function getPerPage() 76 | { 77 | return $this->paginator->PerPage(); 78 | } 79 | 80 | /** 81 | * Get the url for the given page. 82 | * 83 | * @param int $page 84 | * 85 | * @return string 86 | */ 87 | public function getUrl($page) 88 | { 89 | return $this->paginator->Url($page); 90 | } 91 | 92 | /** 93 | * Get the paginator instance. 94 | * 95 | * @return \Illuminate\Paginator\Paginator 96 | */ 97 | public function getPaginator() 98 | { 99 | return $this->paginator; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/Cyvelnet/Laravel5Fractal/Laravel5FractalServiceProvider.php: -------------------------------------------------------------------------------- 1 | publishes([$source_config => 'config/fractal.php'], 'config'); 27 | 28 | $this->loadViewsFrom(__DIR__.'/../../views', 'fractal'); 29 | } 30 | 31 | /** 32 | * Register the service provider. 33 | * 34 | * @return void 35 | */ 36 | public function register() 37 | { 38 | $source_config = __DIR__.'/../../config/fractal.php'; 39 | $this->mergeConfigFrom($source_config, 'fractal'); 40 | 41 | $this->app->singleton('fractal', function ($app) { 42 | // retrieves configurations 43 | 44 | $autoload = $app['config']->get('fractal.autoload'); 45 | $input_key = $app['config']->get('fractal.input_key'); 46 | $exclude_key = $app['config']->get('fractal.exclude_key'); 47 | $serializer = $app['config']->get('fractal.serializer'); 48 | 49 | // creating fractal manager instance 50 | $manager = new Manager(); 51 | $factalNamespace = 'League\\Fractal\\Serializer\\'; 52 | 53 | $loadSerializer = (class_exists($factalNamespace.$serializer)) ? 54 | $factalNamespace.$serializer : $serializer; 55 | 56 | $manager->setSerializer(new $loadSerializer()); 57 | 58 | if ($autoload === true and $includes = $app['request']->input($input_key)) { 59 | $manager->parseIncludes($includes); 60 | } 61 | 62 | if ($app['request']->has($exclude_key)) { 63 | $manager->parseExcludes($app['request']->input($exclude_key)); 64 | } 65 | 66 | return new FractalServices($manager, $app['app']); 67 | }); 68 | $this->app->alias('fractal', FractalServices::class); 69 | 70 | // register our command here 71 | $this->app->singleton('command.transformer.generate', function ($app) { 72 | return new TransformerGeneratorCommand($app['config'], $app['view'], $app['files'], $app); 73 | }); 74 | 75 | $this->commands('command.transformer.generate'); 76 | } 77 | 78 | /** 79 | * Get the services provided by the provider. 80 | * 81 | * @return array 82 | */ 83 | public function provides() 84 | { 85 | return ['fractal', 'command.transformer.generate']; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/config/fractal.php: -------------------------------------------------------------------------------- 1 | env('FRACTAL_AUTOLOAD', true), 14 | 15 | /* 16 | |-------------------------------------------------------------------------- 17 | | Input key 18 | |-------------------------------------------------------------------------- 19 | | 20 | | Parameter key to include extra data in transformer class from request url 21 | | * only values defined in transformer class $availableIncludes will be available 22 | | 23 | */ 24 | 'input_key' => env('FRACTAL_INPUT_KEY', 'include'), 25 | 26 | /* 27 | |-------------------------------------------------------------------------- 28 | | Exclude key 29 | |-------------------------------------------------------------------------- 30 | | 31 | | Parameter key to excludes from request url, included resources specified in transformer class 32 | | 33 | */ 34 | 'exclude_key' => env('FRACTAL_EXCLUDE_KEY', 'exclude'), 35 | 36 | /* 37 | |-------------------------------------------------------------------------- 38 | | Transformer class namespace 39 | |-------------------------------------------------------------------------- 40 | | 41 | | Base namespace for generated transformer class 42 | | 43 | */ 44 | 'namespace' => env('FRACTAL_NAMESPACE', 'App\Transformers'), 45 | 46 | /* 47 | |-------------------------------------------------------------------------- 48 | | Transformer store path 49 | |-------------------------------------------------------------------------- 50 | | 51 | | Store path where generated transformer class 52 | | 53 | */ 54 | 'directory' => env('FRACTAL_DIRECTORY', 'Transformers/'), 55 | 56 | /* 57 | |-------------------------------------------------------------------------- 58 | | Transformer parent class 59 | |-------------------------------------------------------------------------- 60 | | 61 | | the parent class a transformer class extend in FQCN 62 | | By default \League\Fractal\TransformerAbstract use 63 | | * The custom parent class must extends \League\Fractal\TransformerAbstract class 64 | */ 65 | 'abstract_parent' => null, 66 | 67 | /* 68 | |-------------------------------------------------------------------------- 69 | | Models/Entities path 70 | |-------------------------------------------------------------------------- 71 | | 72 | | Path where transformer looking for entities to generate transformation data. 73 | | 74 | */ 75 | 'model_namespace' => 'App', 76 | 77 | /* 78 | |-------------------------------------------------------------------------- 79 | | Serializer 80 | |-------------------------------------------------------------------------- 81 | | 82 | | Parameter key to excludes included resources specified in transformer class 83 | | * you are required to provide full namespace for custom serializer 84 | | 85 | */ 86 | 'serializer' => env('FRACTAL_SERIALIZER', 'ArraySerializer'), 87 | // DataArraySerializer,JsonApiSerializer, ArraySerializer 88 | 89 | ]; 90 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![StyleCI](https://styleci.io/repos/32406904/shield)](https://styleci.io/repos/32406904) 2 | [![Build Status](https://travis-ci.org/Cyvelnet/laravel5-fractal.svg?branch=master)](https://travis-ci.org/Cyvelnet/laravel5-fractal) 3 | [![Total Downloads](https://poser.pugx.org/cyvelnet/laravel5-fractal/downloads)](https://packagist.org/packages/cyvelnet/laravel5-fractal) 4 | [![Latest Stable Version](https://poser.pugx.org/cyvelnet/laravel5-fractal/v/stable)](https://packagist.org/packages/cyvelnet/laravel5-fractal) 5 | [![Latest Unstable Version](https://poser.pugx.org/cyvelnet/laravel5-fractal/v/unstable)](https://packagist.org/packages/cyvelnet/laravel5-fractal) 6 | [![License](https://poser.pugx.org/cyvelnet/laravel5-fractal/license)](https://packagist.org/packages/cyvelnet/laravel5-fractal) 7 | 8 | # laravel5-fractal 9 | A simple fractal service provider and transformer generator for laravel 5 and lumen 10 | 11 | * [Installation](#installation) 12 | * [Config](#config) 13 | * [Command](#command) 14 | * [Usage](#usage) 15 | * [Trait](#trait) (Optional feature >= 2.1.3) 16 | * [Sub Relationship Modifier](#trait) (Optional feature >=2.4.0) 17 | * [Extra](#extra) Extra 18 | 19 | ## Installation 20 | 21 | #### Laravel 22 | Require this package with composer using the following command: 23 | ````bash 24 | composer require cyvelnet/laravel5-fractal 25 | ```` 26 | After updating composer, add the ServiceProvider to the providers array in config/app.php 27 | ````php 28 | Cyvelnet\Laravel5Fractal\Laravel5FractalServiceProvider::class, 29 | ```` 30 | 31 | and register Facade 32 | And optionally add a new line to the `aliases` array: 33 | 34 | 'Fractal' => Cyvelnet\Laravel5Fractal\Facades\Fractal::class 35 | 36 | #### Lumen 37 | register service provider in /bootstrap/app.php for lumen 38 | 39 | ````php 40 | $app->register(Cyvelnet\Laravel5Fractal\Laravel5FractalServiceProvider::class); 41 | ```` 42 | 43 | and uncomment the line 44 | 45 | ````php 46 | $app->withFacades(); 47 | ```` 48 | 49 | and finally register Facade with 50 | 51 | ````php 52 | class_alias(Cyvelnet\Laravel5Fractal\Facades\Fractal::class, 'Fractal'); 53 | ```` 54 | 55 | ### Config 56 | You can also publish the config file to change implementations to suits you. 57 | 58 | ````bash 59 | php artisan vendor:publish --provider="Cyvelnet\Laravel5Fractal\Laravel5FractalServiceProvider" 60 | ```` 61 | 62 | ##### Automatic sub resources injection. 63 | 64 | Auto inject/embed sub resources are disabled by default, to enable this feature, edit ``config/fractal.php`` and set 65 | 66 | ``autoload => true`` 67 | 68 | 69 | ### Command 70 | `cyvelnet/fractal` come with a helpful commandline to assist your api transformation, just type and your Eloquent model attributes will be added to your transform array automatically 71 | ````bash 72 | // generate a empty transformer 73 | php artisan make:transformer UserTransformer 74 | 75 | // generate a modeled transformer 76 | php artisan make:transformer UserTransformer -m User 77 | ```` 78 | 79 | ### Usage 80 | 81 | ### Fractal::item(); 82 | Transform a single record 83 | ```php 84 | 85 | $user = User::find(1); 86 | 87 | Fractal::item($user, new UserTransformer()); 88 | 89 | ``` 90 | 91 | ### Fractal::collection(); 92 | Transform a collection of records 93 | ```php 94 | 95 | $users = User::where('activated', true)->get(); 96 | 97 | // $resourceKey is optional for most serializer, but recommended to set for JsonApiSerializer 98 | $resourceKey = 'user'; 99 | 100 | Fractal::collection($users, new UserTransformer(), $resourceKey); 101 | 102 | ``` 103 | 104 | ### Fractal::includes() 105 | Inject sub resources 106 | ```php 107 | 108 | Fractal::includes('orders') // where 'orders' is defined in your transformer class's $availableIncludes array 109 | 110 | ``` 111 | 112 | ### Fractal::excludes() 113 | Remove sub resources 114 | ```php 115 | 116 | Fractal::excludes('orders') 117 | 118 | ``` 119 | 120 | ### Fractal::setSerializer() 121 | Change transformer serializer 122 | ```php 123 | 124 | Fractal::setSerializer(\Acme\MySerializer); // where MySerializer is a class extends \League\Fractal\Serializer\SerializerAbstract 125 | 126 | ``` 127 | 128 | ### Fractal::fieldsets() 129 | add sparse fieldset 130 | ```php 131 | 132 | Fractal::fieldsets(['orders' => 'item,qty,total,date_order']) 133 | ``` 134 | 135 | ### Fractal::addMeta() 136 | add extra meta data to root 137 | ```php 138 | 139 | // specify with single meta data 140 | Fractal::addMeta($key = 'metaKey', $data = 'metaData') 141 | 142 | // add an array of meta data 143 | Fractal::addMeta([ 144 | 'key1' => 'data1', 145 | 'key2' => 'data2' 146 | ]) 147 | 148 | ``` 149 | 150 | ## Trait 151 | 152 | https://github.com/Cyvelnet/laravel5-fractal/wiki/Transformable-Trait 153 | 154 | ## Sub Relationship Modifier 155 | 156 | https://github.com/Cyvelnet/laravel5-fractal/wiki/Sub-Relationship-Modifier 157 | 158 | ## Extra 159 | 160 | https://github.com/Cyvelnet/laravel5-fractal/wiki/Custom-TransformerableAbstract-class 161 | 162 | -------------------------------------------------------------------------------- /src/Cyvelnet/Laravel5Fractal/Commands/TransformerGeneratorCommand.php: -------------------------------------------------------------------------------- 1 | config = $config; 54 | $this->view = $view; 55 | $this->filesystem = $filesystem; 56 | $this->app = $app; 57 | } 58 | 59 | /** 60 | * Execute the console command. 61 | * 62 | * @return mixed 63 | */ 64 | public function handle() 65 | { 66 | try { 67 | // replace all space after ucwords 68 | $class_name = preg_replace('/\s+/', '', ucwords($this->argument('name'))); 69 | 70 | //retrieves store directory configuration 71 | $directory = $this->option('directory') ? $this->appPath($this->option('directory')) : $this->appPath($this->config->get('fractal.directory')); 72 | 73 | $model = ucwords($this->option('model')); 74 | 75 | $modelClass = $this->getModelNamespace($model); 76 | 77 | $transformerAttrs = $this->getModelColumns($model); 78 | 79 | //retrieves namespace configuration 80 | $namespace = $this->option('namespace') ? $this->option('namespace') : $this->config->get('fractal.namespace'); 81 | 82 | list($class, $namespace, $directory) = $this->getTransformerProperties($class_name, $namespace, $directory); 83 | 84 | is_dir($directory) ?: $this->filesystem->makeDirectory($directory, 0755, true); 85 | 86 | $create = true; 87 | 88 | // transformer store path 89 | $transformer = "{$directory}/{$class}"; 90 | 91 | if ($this->filesystem->exists("{$transformer}.php")) { 92 | if ($usrResponse = strtolower($this->ask( 93 | "The filesystem ['{$class}'] already exists, overwrite? [y/n]", 94 | null 95 | )) 96 | ) { 97 | switch ($usrResponse) { 98 | case 'y': 99 | $backupFile = "{$directory}/{$class}.php"; 100 | 101 | while ($this->filesystem->exists($backupFile)) { 102 | $prefix = (new \DateTime())->format('Y_m_d_His'); 103 | $backupFile = "{$directory}/{$prefix}_{$class}.php"; 104 | } 105 | rename("{$directory}/{$class}.php", $backupFile); 106 | $this->info("A backup has been generated at {$backupFile}"); 107 | break; 108 | default: 109 | $this->info('No filesystem has been created.'); 110 | $create = false; 111 | } 112 | } 113 | } 114 | 115 | // loading transformers template from views 116 | $view = $this->view->make( 117 | 'fractal::transformer', 118 | [ 119 | 'namespace' => $namespace, 120 | 'class_name' => $class, 121 | 'attributes' => $transformerAttrs, 122 | 'modelClass' => $model ? $modelClass : null, 123 | 'model' => $model, 124 | 'parentClass' => $this->config->get( 125 | 'fractal.abstract_parent', 126 | 'TransformerAbstract' 127 | ) ?: 'TransformerAbstract', 128 | ] 129 | ); 130 | 131 | if ($create) { 132 | $this->filesystem->put("{$directory}/{$class}.php", $view->render()); 133 | $this->info("The class {$class} generated successfully."); 134 | } 135 | } catch (\Exception $e) { 136 | $this->error("Transformer creation failed due to : {$e->getMessage()}"); 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/Cyvelnet/Laravel5Fractal/Commands/Command.php: -------------------------------------------------------------------------------- 1 | getModelNamespace($class); 100 | 101 | if ($class) { 102 | if (class_exists($classNamespace)) { 103 | $model = new \ReflectionClass($classNamespace); 104 | 105 | if ($model->isSubclassOf('Illuminate\Database\Eloquent\Model')) { 106 | $mdl = $this->app->make($classNamespace); 107 | $table = $mdl->getTable(); 108 | 109 | if (is_array($table)) { 110 | $table = array_first($table); 111 | } 112 | 113 | $table = $mdl->getConnection()->getTablePrefix().$table; 114 | $schema = $mdl->getConnection()->getDoctrineSchemaManager($table); 115 | 116 | $database = null; 117 | if (strpos($table, '.')) { 118 | list($database, $table) = explode('.', $table); 119 | } 120 | 121 | $columns = Arr::except($schema->listTableColumns($table, $database), $mdl->getHidden()); 122 | 123 | foreach ($columns as $column) { 124 | if ($column->getType() instanceof \Doctrine\DBAL\Types\JsonArrayType) { 125 | continue; 126 | } 127 | 128 | $castTo = $this->getCasting($column->getType()); 129 | 130 | $attributes[] = ['column' => $column->getName(), 'casts' => $castTo]; 131 | } 132 | 133 | return $attributes; 134 | } 135 | } else { 136 | $this->error("Your model {$class} was not found in {$this->config->get('fractal.model_namespace')}\\ \r\nIf this is the first time you get this message, try to update /config/fractal.php to make changes to model_namespace accordingly."); 137 | exit; 138 | } 139 | } 140 | 141 | // use as a default attribute 142 | return [ 143 | ['column' => 'id', 'casts' => null], 144 | ]; 145 | } 146 | 147 | /** 148 | * get value cast type. 149 | * 150 | * @param $type 151 | * 152 | * @return null|string 153 | */ 154 | protected function getCasting($type) 155 | { 156 | if ($type instanceof \Doctrine\DBAL\Types\DecimalType or $type instanceof 157 | \Doctrine\DBAL\Types\FloatType 158 | ) { 159 | return 'double'; 160 | } else { 161 | if ($type instanceof \Doctrine\DBAL\Types\IntegerType or $type instanceof \Doctrine\DBAL\Types\BigIntType or $type instanceof 162 | \Doctrine\DBAL\Types\SmallIntType 163 | ) { 164 | return 'int'; 165 | } 166 | } 167 | } 168 | 169 | /** 170 | * get model namespace from a class name. 171 | * 172 | * @param $class 173 | * 174 | * @return string 175 | */ 176 | protected function getModelNamespace($class) 177 | { 178 | $namespace = $this->config->get('fractal.model_namespace'); 179 | 180 | return "\\{$namespace}\\{$class}"; 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /src/Cyvelnet/Laravel5Fractal/Traits/Transformable.php: -------------------------------------------------------------------------------- 1 | getService()->addMeta($key, $data); 24 | 25 | return $this; 26 | } 27 | 28 | /** 29 | * transform resource collection. 30 | * 31 | * @param $data 32 | * @param \League\Fractal\TransformerAbstract|callable|\Closure $transformer 33 | * @param null $resourceKey 34 | * @param PaginatorInterface $adapter 35 | * 36 | * @return \Cyvelnet\Laravel5Fractal\Adapters\ScopeDataAdapter|mixed 37 | */ 38 | public function collection($data, $transformer = null, $resourceKey = null, PaginatorInterface $adapter = null) 39 | { 40 | if (!$transformer) { 41 | $transformer = $this->getTransformer(); 42 | } 43 | 44 | return $this->getService()->collection($data, $transformer, $resourceKey, $adapter); 45 | } 46 | 47 | /** 48 | * excludes sub level from data transformer. 49 | * 50 | * @param string|array $excludes 51 | * 52 | * @return $this 53 | */ 54 | public function excludes($excludes) 55 | { 56 | $this->getService()->excludes($excludes); 57 | 58 | return $this; 59 | } 60 | 61 | /** 62 | * Parse field include parameter. 63 | * 64 | * @param array $fieldsets Array of fields to include. It must be an array 65 | * whose keys are resource types and values a string 66 | * of the fields to return, separated by a comma 67 | * 68 | * @return $this 69 | */ 70 | public function fieldsets($fieldsets = []) 71 | { 72 | $this->getService()->fieldsets($fieldsets); 73 | 74 | return $this; 75 | } 76 | 77 | /** 78 | * includes sub level data transformer. 79 | * 80 | * @param string|array $includes 81 | * 82 | * @return $this 83 | */ 84 | public function includes($includes) 85 | { 86 | $this->getService()->includes($includes); 87 | 88 | return $this; 89 | } 90 | 91 | /** 92 | * transform a single resource. 93 | * 94 | * @param $data 95 | * @param null $transformer 96 | * @param null $resourceKey 97 | * 98 | * @return \Cyvelnet\Laravel5Fractal\Adapters\ScopeDataAdapter 99 | */ 100 | public function item($data, $transformer = null, $resourceKey = null) 101 | { 102 | if (!$transformer) { 103 | $transformer = $this->getTransformer(); 104 | } 105 | 106 | return $this->getService()->item($data, $transformer, $resourceKey); 107 | } 108 | 109 | /** 110 | * set data serializer. 111 | * 112 | * @param \League\Fractal\Serializer\SerializerAbstract $serializer 113 | */ 114 | public function serializer($serializer) 115 | { 116 | $this->getService()->setSerializer($serializer); 117 | } 118 | 119 | /** 120 | * transform data. 121 | * 122 | * @param $data 123 | * @param null|mixed|\callable $transformer 124 | * @param null $resourceKey 125 | * @param \League\Fractal\Pagination\PaginatorInterface|null $adapter 126 | * 127 | * @return \Cyvelnet\Laravel5Fractal\Adapters\ScopeDataAdapter|mixed 128 | */ 129 | public function transform($data, $transformer = null, $resourceKey = null, PaginatorInterface $adapter = null) 130 | { 131 | if (!$transformer) { 132 | $transformer = $this->getTransformer(); 133 | } 134 | 135 | $fractal = $this->getService(); 136 | 137 | if ($this->isCollection($data)) { 138 | return $fractal->collection($data, $transformer, $resourceKey, $adapter); 139 | } 140 | 141 | return $fractal->item($data, $transformer, $resourceKey); 142 | } 143 | 144 | /** 145 | * classes that should recognized as a collection. 146 | * 147 | * @return array 148 | */ 149 | protected function getCollectionClass() 150 | { 151 | return []; 152 | } 153 | 154 | /** 155 | * get transformer serializer defined in class scope. 156 | * 157 | * @return bool|string 158 | */ 159 | protected function getSerializer() 160 | { 161 | if (property_exists($this, $serializer = $this->getSerializerProperty())) { 162 | return $serializer; 163 | } 164 | 165 | return false; 166 | } 167 | 168 | /** 169 | * get transformer defined in class scope. 170 | * 171 | * @return mixed|bool 172 | */ 173 | protected function getTransformer() 174 | { 175 | if (property_exists($this, $transformer = $this->getTransformerProperty())) { 176 | return app($this->{$transformer}); 177 | } 178 | 179 | return false; 180 | } 181 | 182 | /** 183 | * get transformer class property key. 184 | * 185 | * @return string 186 | */ 187 | protected function getTransformerProperty() 188 | { 189 | if (property_exists($this, 'transformProperty')) { 190 | return $this->transformProperty; 191 | } 192 | 193 | return 'transformer'; 194 | } 195 | 196 | /** 197 | * get transformer class property key. 198 | * 199 | * @return string 200 | */ 201 | protected function getSerializerProperty() 202 | { 203 | if (property_exists($this, 'serializerProperty')) { 204 | return $this->getSerializerProperty; 205 | } 206 | 207 | return 'serializer'; 208 | } 209 | 210 | /** 211 | * determine if an object should be recognize as collection. 212 | * 213 | * @return bool 214 | */ 215 | protected function isCollection($data) 216 | { 217 | if (is_array($data) || $data instanceof \Illuminate\Support\Collection || $data instanceof Paginator) { 218 | return true; 219 | } 220 | 221 | $length = count($this->getCollectionClass()); 222 | 223 | for ($i = 0; $i < $length; $i++) { 224 | $class = \Illuminate\Support\Arr::get($this->getCollectionClass(), $i); 225 | 226 | if ($data instanceof $class) { 227 | return true; 228 | } 229 | } 230 | 231 | return false; 232 | } 233 | 234 | /** 235 | * get a fractal services instance. 236 | * 237 | * @return \Cyvelnet\Laravel5Fractal\FractalServices 238 | */ 239 | protected function getService() 240 | { 241 | return app('fractal')->setSerializer($this->getSerializer()); 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /src/Cyvelnet/Laravel5Fractal/FractalServices.php: -------------------------------------------------------------------------------- 1 | manager = $manager; 58 | $this->autoload = $app['config']->get('fractal.autoload'); 59 | $this->input_key = $app['config']->get('fractal.input_key'); 60 | $this->exclude_key = $app['config']->get('fractal.exclude_key'); 61 | $this->request = $app['request']; 62 | } 63 | 64 | /** 65 | * add additional meta data to transformed data. 66 | * 67 | * @param $key 68 | * @param $data 69 | * 70 | * @return $this 71 | */ 72 | public function addMeta($key, $data = null) 73 | { 74 | if (is_array($key)) { 75 | $this->meta += $key; 76 | } else { 77 | $this->meta[$key] = $data; 78 | } 79 | 80 | return $this; 81 | } 82 | 83 | /** 84 | * transform resource collection. 85 | * 86 | * @param $items 87 | * @param \League\Fractal\TransformerAbstract|callable|\Closure $transformer 88 | * @param null $resourceKey 89 | * @param PaginatorInterface $adapter 90 | * 91 | * @return \Cyvelnet\Laravel5Fractal\Adapters\ScopeDataAdapter|mixed 92 | */ 93 | public function collection( 94 | $items, 95 | $transformer, 96 | $resourceKey = null, 97 | PaginatorInterface $adapter = null 98 | ) { 99 | $resources = new Collection($items, $transformer, $resourceKey); 100 | 101 | $this->applyMetaValue($resources); 102 | 103 | if ($adapter) { 104 | $this->withPaginator($resources, $adapter); 105 | } 106 | 107 | if ($items instanceof LengthAwarePaginator) { 108 | $adapter = new IlluminatePaginatorAdapter($items); 109 | $this->withPaginator($resources, $adapter); 110 | } 111 | 112 | return $this->scope($resources); 113 | } 114 | 115 | /** 116 | * excludes sub level from data transformer. 117 | * 118 | * @param string|array $excludes 119 | * 120 | * @return $this 121 | */ 122 | public function excludes($excludes) 123 | { 124 | if (is_string($excludes)) { 125 | $excludes = explode(',', $excludes); 126 | } 127 | 128 | // when autoload is enable, we need to merge user requested includes with the predefined includes. 129 | if ($this->autoload and $this->request->get($this->exclude_key)) { 130 | $excludes = array_merge($excludes, explode(',', $this->request->get($this->exclude_key))); 131 | } 132 | 133 | $this->manager->parseExcludes($excludes); 134 | 135 | return $this; 136 | } 137 | 138 | /** 139 | * Parse field parameter. 140 | * 141 | * @param array $fieldsets Array of fields to include. It must be an array 142 | * whose keys are resource types and values a string 143 | * of the fields to return, separated by a comma 144 | * 145 | * @return $this 146 | */ 147 | public function fieldsets(array $fieldsets = []) 148 | { 149 | $this->fieldsets = $fieldsets; 150 | 151 | return $this; 152 | } 153 | 154 | /** 155 | * @return mixed 156 | */ 157 | public function getManager() 158 | { 159 | return $this->manager; 160 | } 161 | 162 | /** 163 | * includes sub level data transformer. 164 | * 165 | * @param string|array $includes 166 | * 167 | * @return $this 168 | */ 169 | public function includes($includes) 170 | { 171 | if (is_string($includes)) { 172 | $includes = explode(',', $includes); 173 | } 174 | 175 | // when autoload is enable, we need to merge user requested includes with the predefined includes. 176 | if ($this->autoload and $this->request->get($this->input_key)) { 177 | $includes = array_merge($includes, explode(',', $this->request->get($this->input_key))); 178 | } 179 | 180 | $this->manager->parseIncludes($includes); 181 | 182 | return $this; 183 | } 184 | 185 | /** 186 | * transform a single resource. 187 | * 188 | * @param $item 189 | * @param \League\Fractal\TransformerAbstract|callable|\Closure $transformer 190 | * @param null $resourceKey 191 | * 192 | * @return \Cyvelnet\Laravel5Fractal\Adapters\ScopeDataAdapter|mixed 193 | */ 194 | public function item($item, $transformer, $resourceKey = null) 195 | { 196 | $resource = new Item($item, $transformer, $resourceKey); 197 | 198 | $this->applyMetaValue($resource); 199 | 200 | return $this->scope($resource); 201 | } 202 | 203 | /** 204 | * set data transformation recursion limit. 205 | * 206 | * @param $limit 207 | * 208 | * @return $this 209 | */ 210 | public function setRecursionLimit($limit) 211 | { 212 | $this->manager->setRecursionLimit($limit); 213 | 214 | return $this; 215 | } 216 | 217 | /** 218 | * set data serializer. 219 | * 220 | * @param \League\Fractal\Serializer\SerializerAbstract $serializer 221 | * 222 | * @return $this 223 | */ 224 | public function setSerializer($serializer) 225 | { 226 | if (!$serializer) { 227 | return $this; 228 | } 229 | 230 | $this->manager->setSerializer($serializer); 231 | 232 | return $this; 233 | } 234 | 235 | private function applyMetaValue($resource) 236 | { 237 | $resource->setMeta($this->meta); 238 | } 239 | 240 | /** 241 | * return result scope. 242 | * 243 | * @param ResourceInterface $resource 244 | * 245 | * @return \Cyvelnet\Laravel5Fractal\Adapters\ScopeDataAdapter 246 | */ 247 | private function scope(ResourceInterface $resource) 248 | { 249 | return new ScopeDataAdapter($this->manager->parseFieldsets($this->fieldsets)->createData($resource)); 250 | } 251 | 252 | /** 253 | * set a paginator meta when a paginator instance detected. 254 | * 255 | * @param $items 256 | * @param $resources 257 | * @param $adapter 258 | */ 259 | private function withPaginator(&$resources, $adapter) 260 | { 261 | $resources->setPaginator($adapter); 262 | } 263 | } 264 | --------------------------------------------------------------------------------