Download the PHP package whitedigital-eu/entity-resource-mapper-bundle without Composer
On this page you can find all versions of the php package whitedigital-eu/entity-resource-mapper-bundle. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download whitedigital-eu/entity-resource-mapper-bundle
More information about whitedigital-eu/entity-resource-mapper-bundle
Files in whitedigital-eu/entity-resource-mapper-bundle
Package entity-resource-mapper-bundle
Short Description Bundle to map Doctrine entity object to and from API resource object.
License MIT
Informations about the package entity-resource-mapper-bundle
Entity Resource Mapper Bundle
1) Extends Symfony / Api Platform functionality by helping to map Doctrine entity objects with Api Platform resource objects and offers other helpers such as filters, JSON Functions, etc.
2) Implements AuthorizationService which centralizes all authorization configuration and provides methods for authorizing resources in:
- Data provider - collection get
- Data provider - item get
- Data persister - item post/put/patch
- Data persister - item delete
- Individual resource in EntityToResourceMapper
Requirements
PHP 8.1+
Symfony 6.3+
Installation
The recommended way to install is via Composer:
Configuration
ClassMapper service
You should create ClassMapper service configuration file, for example:
and register it as configurator for ClassMapper service in your services.yaml file:
Additionally, you can use Mapping attribute to register mapping:
Filters
Following filters are currently available (filters works as described in Api Platform docs, except for comments below):
- ResourceBooleanFilter
- ResourceDateFilter (throws exception, if value is not a valid DateTime object)
- ResourceEnumFilter (same as SearchFilter but with explicit documentation)
- ResourceExistsFilter
- ResourceJsonFilter (new filter)
- ResourceNumericFilter
- ResourceOrderFilter (allows ordering by json values)
- ResourceOrderCustomFilter (Order filter which will order by custom SELECT fields, which are not included in root alias nor joins)
- ResourceRangeFilter
- ResourceSearchFilter
JSON Functions
Following PostgreSQL functions are available in Doctrine and used in ResourceJsonFilter and ResourceOrderFilter:
- JSONB_PATH_EXISTS(%s, %s) - PostgreSQL function jsonb_path_exists(%s::jsonb, %s)
- JSON_GET_TEXT(%s, %s) - PostgreSQL alias for %s->>%s
- JSON_ARRAY_LENGTH(%s) - PostgreSQL function json_array_length(%s)
- JSON_CONTAINS(%s, %s) - PostgreSQL alias for %s::jsonb @> '%s'
DBAL Types
This bundle comes with and autoconfigures following dbal types to use UTC time zone:
- date
- datetime
- date_immutable
- datetime_immutable
Security
Available operation types:
AuthorizationService::ALL
Includes all of the belowAuthorizationService::COL_GET
Collection GETAuthorizationService::ITEM_GET
Item GETAuthorizationService::COL_POST
Collection POSTAuthorizationService::ITEM_PATCH
Item PUT + PATCHAuthorizationService::ITEM_DELETE
Item DELETE
Available grant types:
GrantType::ALL
resource fully availableGrantType::LIMITED
resource is available with limitationsGrantType::NONE
resource not available
AuthorizationService Configurator must be implemented.
register it as service:
If setAuthorizationOverride
closure is set, it will be called with current object (resource or entity) and if it returns true, authorization will be skipped.
Use following methods:
-
In DataProvider, getCollection:
-
In DataProvider, getItem:
-
In DataPersister, persist:
-
In DataPersister, remove:
- In any Resource, if you have defined its grant as LIMITED, you must add attribute to BaseResource class, to define access resolver configurations for each of the resource classes
Same class must also set following property with correct normalization group:
Property visibility check
Sometimes you want to return all items in endpoint but want to limit properties returned based on user roles. To do so, you need to set GrantType::LIMITED
to
role and operation you want to have this visibility check and add #[VisibleProperty]
attribute to resource where this check should be done.
#[VisibleProperty]
attribute takes 2 parameters: ownerProperty
and properties
. properties
is an array of all properties you want to SHOW
. ownerProperty
is
the name of property which to check against current logged in user.
IMPORTANT: If resource has GrantType::LIMITED to some role for get or get_collection operations, at least one access resolver or
#[VisibleProperty]
must be set!
Explicit check if all roles are configured in authorization service
If you want explicitly check if all project defined roles are fully configured in authorization service, you can configure this check by passing BackedEnum containing all needed roles to configuration.
Default value is
[]
, so without this configuration check will not be triggered.
or
This enum must be backed and contain all needed roles with ROLE_
prefix like this:
Now if you don't have ROLE_USER or ROLE_ADMIN grants configured for any resource operation you passed in AuthorizationService->setServices()
, exception will be thrown.
Public resource access
If it is required to access any resource without authorization (by default this is forbidden), you can use AuthorizationServiceConfigurator
to allow specific operations for AuthenticatedVoter::PUBLIC_ACCESS
. To do so, configure needed operations using GrantType::ALL
. Only
GrantType::ALL
is allowed to be used (no option for GrantType::LIMITED
) and you do not need to set GrantType::NONE
for public
access.
Example:
Menu Builder
This package ships with a menu builder functionality, that allows to define the overall menu structure and allows for dynamic menu building based on current user limitations (authorization, rules)
To use menu builder service, you must first create a configurator class for this service that implements WhiteDigital\EntityResourceMapper\Interface\MenuBuilderServiceConfiguratorInterface
Register the configurator class as a service:
And finally you can use the menubuilder and retrieve the filtered menu by calling the MenuBuilderService like so:
Base provider and processor
In most cases way how to read or write data to database is the same, so this package provides AbstractDataProcessor
and AbstractDataProvider
that implements base logic for api platform.
Maker part of this package uses these clases for generation as well. Using these abstractions will take away need to
duplicate code for each entity/resource. As these are abstractions, you can always override any function of them when
needed.
Extended api resource
Other whitedigital-eu
packages may come with api resources that with some configuration may not be suited for
straight away usage in a project. This is why ExtendedApiResource
is useful to override part of options defined
in default attributes.
For example, take a look at WhiteDigital\Audit\ApiResource\AuditResource
class. It defines api resource.
If you want iri to be /api/vendor/audits
, you have to do the following:
- Create new class that extends resource you want to override
- Add
ExtendedApiResouce
attribute insted ofApiResource
attribute - Pass only those options that you want to override, others will be taken from resource you are extending
ExtendedApiResouce
attribute checks which resource you are extending and overrides options given in extension,
keeping other options same as in parent resource.
IMPORTANT: You need to disable bundled resource using api_platform.openapi.factory decorator, otherwise you will have 2 instances of audit resource: one with
/api/audits
iri and one with/api/vendor/audits
iri.
ApiResource maker
Default configuration options comes based on api-platform
|symfony
recommendations but you can override them like this (default values shown):
namespaces
are there to set up different directories for generated files. So, if you need to put files in different directories/namespaces, you can chnage it as such.
roleSeparator
and space
from defaults
are added to configure separators for groups used in api resource. For example, UserRole
with defaults will become user_role:read
for read group.
apiResourcrSuffix
defines suffix for api resource class name. For example, by default User
entity will make UserResource
api resource class.
Usage
Simply run make:api-resource <EntityName>
where EntityName is entity you want to create api resource for.
Example, make:api-resource User
to make UserResource, UserDataProcessor and UserDataProvider for User entity.
Maker command generates resource properties based on entity variables. This could sometimes be incorrect or not needed, so you can pass --no-properties
option to not generate properties.
By default, maker command will throw an error if you are trying to generate classes that already exist. If for some reason you want to rewrite generated classes, you can pass --delete-if-exists
option.
This option comes in handy on occasion when you have 2 entities, that have relation. Because of specific logical impossibility, to generate resources for both classes automatically, you should:
- run
make:api-resource Entity1 --no-properties
- run
make:api-resource Entity2
- run
make:api-resource Entity1 --delete-if-exists
This command automatically generates ApiFilters for given entity. Default value is to generate them is for first level fields. Like this:
If you don't want to generate any filters, run command by passing level 0
:
If you want generate filters for more levels for subresources, like, parent.createdAt, pass higher level:
Higher level -> deeper subresource filters.
It is obvious that you probably do not need all generated filters, but it is easier to remove than it is to add.
If you want to exclude specific type of filters, you can pass --exclude-<filter>
to skip generation of those filters.
Available filters are:
array
:ResourceJsonFilter
bool
:ResourceBooleanFilter
date
:ResourceDateFilter
enum
:ResourceEnumFilter
numeric
:ResourceNumericFilter
range
:ResourceRangeFilter
search
:ResourceSearchFilter
ResourceOrderFilter
is created from non-excluded numeric
, search
, date
and array
filters.
PHP CS Fixer
IMPORTANT: When running php-cs-fixer, make sure not to format files in
skeleton
folder. Otherwise maker command will stop working.
Validators
This library contains validators for Classifiers. These will only work if Entity/Resource have following structure (not less than this): Entity:
Resource:
As seen in these examples, you need to have a Backed enum (here called ClassifierType
) that you need to validate against.
Example of ClassifierType
is something like this:
Now you can use either CorrectClassifierType
or ClassifierRequiredDataIsSet
validator:
CorrectClassifierType
:
CorrectClassifierType checks if in related resource Classifier is given with correct type:
Now if you pass resource that has any other type (like ClassifierType::TWO
for example) to this resource, error will be thrown.
ClassifierRequiredDataIsSet
:
Sometimes you may need extra data in Classifier and may be mandatory. For this ClassifierRequiredDataIsSet can be used to check if this
data is passed. This is used on ClassifierResource
:
And now when creating a new Classifier with type ONE
, an error will be thrown if data does not contain value with key test1
Tests
Run tests by:
TODO
- performance improvements
- explicit joins on dataprovider
- computed properties as querybuilder methods
All versions of entity-resource-mapper-bundle with dependencies
api-platform/core Version ^3.2
doctrine/annotations Version *
doctrine/collections Version *
doctrine/common Version ^3.4
doctrine/dbal Version ^3.7
doctrine/orm Version ^2.19
doctrine/persistence Version *
phpdocumentor/reflection-docblock Version *
psr/log Version *
symfony/config Version ^6.3
symfony/console Version ^6.3
symfony/dependency-injection Version ^6.3
symfony/doctrine-bridge Version ^6.3
symfony/framework-bundle Version ^6.3
symfony/http-foundation Version ^6.3
symfony/http-kernel Version ^6.3
symfony/maker-bundle Version *
symfony/property-access Version ^6.3
symfony/property-info Version ^6.3
symfony/security-bundle Version ^6.3
symfony/security-core Version ^6.3
symfony/serializer Version ^6.3
symfony/service-contracts Version *
symfony/string Version ^6.3
symfony/translation Version ^6.3
symfony/validator Version ^6.3
symfony/yaml Version ^6.3