Why is the dynamic serialization group I've created not allowing a mutation for the specified property? - serialization

I've implemented a Dynamic Serialization group via Context Builder for admin users (adding admin:write). And have assigned this group to the property I want only updatable by an admin via GraphQL.
My implementation at this point is taken directly from https://api-platform.com/docs/core/graphql/#changing-the-serialization-context-dynamically
But when attempting to mutate this property I am given an error that reads Field "roles" is not defined by type updateUserInput.
This makes some sense to me as the schema does not contain this property since it is not in the typical write group. However, the documentation suggests this should be doable. If this is the case, what am I not doing correctly?
Relevant Code:
Context Builder
<?php
namespace App\Serializer;
use ApiPlatform\Core\GraphQl\Serializer\SerializerContextBuilderInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
/**
* Context Builder: Experimental implementation used for constructing what resources are returned.
*/
final class AdminGroupsContextBuilder implements SerializerContextBuilderInterface {
private $decorated;
private $authorizationChecker;
/**
*
*/
public function __construct(SerializerContextBuilderInterface $decorated, AuthorizationCheckerInterface $authorizationChecker) {
$this->decorated = $decorated;
$this->authorizationChecker = $authorizationChecker;
}
/**
*
*/
public function create(?string $resourceClass, string $operationName, array $resolverContext, bool $normalization): array {
$context = $this->decorated->create($resourceClass, $operationName, $resolverContext, $normalization);
$resourceClass = $context['resource_class'] ?? NULL;
if (isset($context['groups']) && $this->authorizationChecker->isGranted('ROLE_ADMIN') && FALSE === $normalization) {
$context['groups'][] = 'admin:input';
}
return $context;
}
}
User Entity Class property definition
/**
* #ORM\Column(type="json")
* #Groups({"read", "admin:write"})
*/
private $roles = [];
Services Definition
App\Serializer\AdminGroupsContextBuilder:
decorates: 'api_platform.graphql.serializer.context_builder'
arguments: [ '#App\Serializer\AdminGroupsContextBuilder.inner' ]
autoconfigure: false

Related

Create different objects based on multiple parameters

I have a REST API. I need to create presentation (DTO) object, but the construction of this object depends on request - it differs in 15%.
I wonder what pattern should I use.
My case:
//presentation-DTO
class Item {
private $name;
private $price;
private $tags;
private $liked; //is Liked by logged user
...
public function __construct(Item $item, bool $liked, ...)
{
$this->name = $item->getName();
$this->price = $item->getPrice();
$this->tags = $item->getTags();
$this->liked = $liked;
...
}
}
When user is not logged in - I don't need $liked
When showing list of items - I don't need $tags
And there are more attributes that works as above.
My first idea was to use Builder principle.
$itemBuilder = new ItemBuilder();
$itemBuilder->setItem($item);
...
if($user) {
$itemBuilder->setUserLiked($userLiked);
...
}
return $itemBuilder->build();
It solves my problem with too many parameters in constructor.
But still, I also don't need all parameters to be constructed - eg. I don't need tags (on lists). As I use lazy load, I don't want my dto constructor to call them.
So I thought, maybe Factory.. but then my problem with too many (and optional) parameters is returning.
How will you solve this?
Sorry I don't have required points to make a comment hence an answer.
What are you trying to do with the Item class. Your class is Item and first parameter is also of type Item. I cannot visualizes how its going to work.
I will prefer to keep business login to set proper properties in a separate class:
/**
* A class for business logic to set the proper properties
*/
class ItemProperties {
private $item;
public $isLogin = false;
public $showList = false;
.....
public function __construct(Item &$item) {
// set all properties;
}
public function getProperties() {
$retVal = [];
if($this->isLogin == true) {
$retVal['liked'] = true;
}
if($this->showList == true) {
$retVal['tags'] = $this->item->getTags();
}
if(....) {
$retVal['...'] = $this->item->.....();
}
return $retVal;
}
}
/**
* DTO
*/
class Item {
public function __construct(ItemProperties $itemProps) {
$this->setItemProps($itemProps);
}
// If you prefer lazy loading here...maybe make it public
// and remove call from constructor.
private function setItemProps(&$itemProps) {
$properties = $itemProps->getProperties();
foreach($properties AS $propName => $propValue) {
$this->$propName = $propValue;
}
}
}
// Usage:
$itemProps = new ItemProperties($Item);
// set other properties if you need to...
$itemProps->isLogin = false;
$item = new Item($itemProps);

Symfony 3 get current user inside entity

I was wondering if there is a way that i can initialize the property owner with an entity User of FOSUserBundle so that it contains the user who created the Post
I want to do this inside the constructor as shown below.
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="post")
* #ORM\Entity(repositoryClass="AppBundle\Repository\PostRepository")
*/
class Post
{
/* here are defined some attributs */
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="posts")
* #ORM\JoinColumn(name="owner", referencedColumnName="id")
*/
private $owner;
public function __construct()
{
$this->owner = /* get current user */ ;
}
}
Is there a way to do this by replacing the comment in the constructor with something ?
Thank you for your answers
No, there isn't. [*]
There are at least two ways to deal with this:
Create your Post entities through a factory service which populates the
owner property:
namespace My\Bundle\EntityFactory;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use My\Bundle\Entity\Post;
class PostFactory
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function createPost()
{
$user = $this->tokenStorage()->getToken()->getUser();
$post = new Post($user);
}
}
(for this example, you will have to modify your Post constructor to
accept the owner as a parameter)
In services.yml:
services:
post_factory:
class: My\Bundle\EntityFactory\PostFactory
arguments: [#security.token_storage]
To create an entity from your controller:
$post = $this->container->get('post_factory')->createPost();
If you can tolerate that the owner will only be set once you persist the
entity, you can use a doctrine event listener:
namespace My\Bundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use My\Bundle\Entity\Post;
class PostOwnerAssignmentListener
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function prePersist(LifecycleEventArgs $event)
{
$entity = $event->getEntity();
if ($entity instanceof Post && !$entity->getOwner()) {
$entity->setOwner($this->tokenStorage->getToken()->getUser());
}
}
}
In services.yml:
services:
post_owner_assignment_listener:
class: My\Bundle\EventListener\PostOwnerAssignmentListener
arguments: [#security.token_storage]
tags:
- { name: doctrine.event_listener, event: prePersit }
The advantage here is that the owner gets assigned no matter how and where
the Post is created.
[*]: Well, technically with the default app.php you could access the
kernel by declaring global $kernel; in your constructor and go from there,
however this is very strongly discouraged and may break in strange and subtle
ways.
I think you are way over-complicating this issue. When you create a new Post in your controller, either in the controller or in the repository do something like this:
use AppBundle\Entity\Post; //at top of controller
$em = $this->getDoctrine()->getManager();
$user = $this->container->get('security.token_storage')->getToken()->getUser();
$post = new Post();
$em->persist( $post );
$post->setOwner( $user );
// set other fields in your post entity
$em->flush();
For Symfony 4+ with Autowiring and Entity event listener:
In /EventListener/PostPrePersistListener.php:
namespace App\EventListener;
use App\Entity\Post;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class PostPrePersistListener
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function prePersist(Post $post, LifecycleEventArgs $event)
{
$post->setOwner($this->tokenStorage->getToken()->getUser());
}
}
In services.yaml:
services:
App\EventListener\PostPrePersistListener:
autowire: true
tags:
- { name: doctrine.orm.entity_listener, entity: 'App\Entity\Post', event: prePersist }
Modifying services.yaml is required as Symfony cannot know that this custom service is tagged to hook on doctrine.event_listener
This works at Entity-level as asked, to ensure Controller do not handle the owner value.

Sylius - Editable Product Code (SKU)

I need to implement an SKU code for products, I was just wondering has anybody any thought on the best way to do this. The SKU needs to be editable after creation.
I feel I have a couple of ways:
(Idealy) I would like to use Product.Code, but this is not an editable field after product creation. I would seem I need to override the ProductType#buildForm class/method to not use AddCodeFormSubscriber(). Although I can't seem to figure out how to get the system to use a different form.
Add SKU to the model of Product and figure out how to add it to the ProductType form and again try and figure out how to use a different form.
I am open to suggestions on how to do it the right way.
Would any of the Sylius developers care to elaborate why they decided to make the Code field un-editable?
If you want use product code as editable field in Sylius Beta.1, you can create ProductType extension to current product type and add your custom subscriber which will make code field editable. I did this in my bundle and it works:
create subscriber class wchich will change disabled state to false:
namespace App\Bundle\Form\EventListener;
/* add required namespaces */
/**
* Custom code subscriber
*/
class CustomCodeFormSubscriber implements EventSubscriberInterface
{
private $type;
private $label;
/**
* #param string $type
* #param string $label
*/
public function __construct($type = TextType::class, $label = 'sylius.ui.code')
{
$this->type = $type;
$this->label = $label;
}
/**
* {#inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
FormEvents::PRE_SET_DATA => 'preSetData',
];
}
/**
* #param FormEvent $event
*/
public function preSetData(FormEvent $event)
{
$disabled = false;
$form = $event->getForm();
$form->add('code', $this->type, ['label' => $this->label, 'disabled' => $disabled]);
}
}
create form extension and use custom subscriber:
namespace App\Bundle\Form\Extension;
use App\Bundle\Form\EventListener\CustomCodeFormSubscriber;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;
use Sylius\Bundle\ProductBundle\Form\Type\ProductType;
/* use other required namespaces etc */
/**
* Extended Product form type
*/
class ProductTypeExtension extends AbstractTypeExtension
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
/* custom stuff for ur form */
$builder->addEventSubscriber(new CustomCodeFormSubscriber());
}
public function getExtendedType()
{
return ProductType::class;
}
}
register your form extension as a service:
app.form.extension.type.product:
class: App\Bundle\Form\Extension\ProductTypeExtension
tags:
- { name: form.type_extension, priority: -1, extended_type: Sylius\Bundle\ProductBundle\Form\Type\ProductType }

How to extend Illuminate\Database\Query\Builder

I'm planning to have a function that will store the sql statement on the Cache using the given second parameter on remember() as the key and whenever the sql statement changes it will run against the database again and overwrite the stored sql, also the cached result, and if not it will take the default cached result by the remember() function.
So I am planning to have something like this on Illuminate\Database\Query\Builder
/**
* Execute the query based on the cached query
*
* #param array $columns
* #return array|static[]
*/
public function getCacheByQuery($columns = array('*'))
{
if ( ! is_null($this->cacheMinutes))
{
list($key, $minutes) = $this->getCacheInfo();
// if the stored sql is the same with the new one then get the cached
// if not, remove the cached query before calling the getCached
$oldSql = self::flag($key);
$newSql = $this->toSql().implode(',', $this->bindings);
if ($newSql!==$oldSql)
{
// remove the cache
\Cache::forget($key);
// update the stored sql
self::updateFlag($key, $newSql);
}
return $this->getCached($columns);
}
return $this->getFresh($columns);
}
public static function updateFlag($flag, $value)
{
$flags = \Cache::get(t().'databaseFlags', []);
$flags[$flag] = $value;
\Cache::put(t().'databaseFlags', $flags, USER_SESSION_EXPIRATION);
}
public static function flag($flag)
{
$flags = \Cache::get(t().'databaseFlags', []);
return #$flags[$flag] ?: false;
}
But the thing is, I don't want to put this directly on Illuminate\Database\Query\Builder since it is just my need for the current application I am working. I'm trying to extend Illuminate\Database\Query\Builder, but the problem is it does not detect the my extension class.
Call to undefined method Illuminate\Database\Query\Builder::getCachedByQuery()
My Extension Class
<?php namespace Lukaserat\Traits;
class QueryBuilder extends \Illuminate\Database\Query\Builder {
/**
* Execute the query based on the caced query
*
* #param array $columns
* #return array|static[]
*/
public function getCachedByQuery($columns = array('*'))
{
if ( ! is_null($this->cacheMinutes))
{
list($key, $minutes) = $this->getCacheInfo();
// if the stored sql is the same with the new one then get the cached
// if not, remove the cached query before calling the getCached
$oldSql = self::flag($key);
$newSql = $this->toSql().implode(',', $this->bindings);
if ($newSql!==$oldSql)
{
// remove the cache
\Cache::forget($key);
// update the stored sql
self::updateFlag($key, $newSql);
}
return $this->getCached($columns);
}
return $this->getFresh($columns);
}
public static function updateFlag($flag, $value)
{
$flags = \Cache::get(t().'databaseFlags', []);
$flags[$flag] = $value;
\Cache::put(t().'databaseFlags', $flags, USER_SESSION_EXPIRATION);
}
public static function flag($flag)
{
$flags = \Cache::get(t().'databaseFlags', []);
return #$flags[$flag] ?: false;
}
}
Implementing on..
<?php
use LaravelBook\Ardent\Ardent;
use Lukaserat\Traits\DataTable;
use Lukaserat\Traits\QueryBuilder as QueryBuilder;
use Illuminate\Support\MessageBag as MessageBag;
class ArdentBase extends Ardent implements InterfaceArdentBase{
use DataTable;
Am I missing something?
Is it correct that I overwrite the get() method on the Illuminate\Database\Query\Builder by renaming the function I made in my extension class from getCachedByQuery to get since I just extending the routine of the get.
I changed
public function getCachedByQuery($columns = array('*'))
to
public function get()
on my Lukaserat\Traits\QueryBuilder
and it is now working as I expected..

TYPO3 - extending an extbase extension with new fields and using these in fluid templates

I'm trying to extend powermail (version 2) with the possibility to add a note for each input field. So far I have created a new extension using extension builder and with a few modifications to ext_tables.php the field show up in the backend. The new field is called 'note' and I thought I could just do something like {field.note} in the fluid template input.html, but that does not work. My model includes the setter and getter:
class Tx_Formnotes_Domain_Model_Powermailnotes extends Tx_Extbase_DomainObject_AbstractEntity {
/**
* note
*
* #var string
*/
protected $note;
/**
* Returns the note
*
* #return string $note
*/
public function getNote() {
return $this->note;
}
/**
* Sets the note
*
* #param string $note
* #return void
*/
public function setNote($note) {
$this->note = $note;
}
}
What else is needed?
Info: I'm using TYPO3 4.7
You could map the powermail model like
config.tx_extbase.persistence.classes {
Tx_Formnotes_Domain_Model_Powermailnotes {
mapping {
tableName = powermailTableName
columns {
exampleMedia.mapOnProperty = media
}
}
}
}
after that you should extend your TCA with these properties. At least you can write setter and getter for each property and use them in your fluid template.