Can't guess how to get a Doctrine instance - php

In a symfony projects, I'm trying to persist a line of an association table (profil_role) composed of two objects (profil and role).
First, I developed The create action in the ProfilRoleController of the second project this way:
/** #var Roles $role */
$em = $this->getDoctrine()->getManager('main_project');
$role = $em->getRepository("MyBundle\Entity\Roles")->find($roleId);
$profil = $em->getRepository("MyBundle\Entity\Profil")->find($profilId);
$profilRole = new ProfilRoles();
$profilRole->setRoleId($role->getId());
$profilRole->setProfilId($profil->getId());
$em->persist($profilRole);
$em->flush();
This part of code, call then the post entity action present in the main project:
/**
* #Rest\View(statusCode=Response::HTTP_CREATED)
* #Rest\Post("/profil_roles")
*/
public function postEntityAction(ProfilRoles $profilRole)
{
$em = $this->getDoctrine()->getManager();
$em->persist($profilRole);
$em->flush();
return $profilRole;
}
When I try to execute my code i'm getting this king of error:
Execution failed for request: POST /api/profil_roles? HTTP/1.1 {"profil":{"id":"12"},"role":{"id":"3"}}: HTTPCode 500, body {"code":500,"message":"Unable to guess how to get a Doctrine instance from the request information."}
I've tried to use the #ParamConverter annotation, but I don't how to use it my case.

try this:
public function postEntityAction() {
$postData = $request->request->all();
$profileRole = $postData['profile_role']
Instead of this:
public function postEntityAction(ProfilRoles $profilRole)

#AlessandroMinoccheri I've tried to be inspired by your reply to do this and i'ts workin, i don't know if it's the correct way.
/**
* #param ProfilRoles $profilRole
* #param Request $request
* #return ProfilRoles
* #Rest\View(statusCode=Response::HTTP_CREATED)
* #Rest\Post("/profil_roles")
*/
public function postEntityAction(Request $request)
{
$profilRole = new ProfilRoles();
$em = $this->getDoctrine()->getManager();
$requete = $request->request->all();
$profilRole->setProfilId($requete['profil']['id']);
$profilRole->setRoleId($requete['role']['id']);
$em->persist($profilRole);
$em->flush();
return $profilRole;
}

Related

PHP SOAP insert data StructType wsdltophp

I am working in a project where I must call SOAP WS. I used WSDLtoPHP, that's really helpful.
I can READ data, and now I would like to create new item with the web services. But when I tried to insert data in the field Nom, I have an error, because the soap server thinks I am trying to insert my data ($nom) inside the attribute NomVide of the field Nom, of the generated xml structure with my code:
<ven1:Nom NomVide="$nom"></ven1:Nom>
$createClient = $SC->S001_Creation_Client(new \StructType\S001_Creation_Client(
new \StructType\RootWSReturnError(
new \StructType\Header("","","","","",array(),"","","","","","","","","","","",array(),"",0,0,"",array(),array(),"","","","","","","","","","","","","","","","","","","","",0,0,"","",array(),"","","","",0,0,0,0,0,0,0),null),
new \StructType\RootWSVenteParametres (array( new \StructType\Vente (array("secret_key")))),
new \StructType\RootWSVenteClient(
array(new \StructType\Client(
new \StructType\General(
"3333",
array(),
array(),
null,
new \StructType\Nom ($nom),
new \StructType\NomRecherche ($nomrecherche),
new \StructType\Nom2 ($nom2),
new \StructType\Marque1($marque1),
new \StructType\Marque2 ($marque2),
new \StructType\Adresse1 (),
new \StructType\Adresse2 (),
new \StructType\CodePostal(),
new \StructType\Ville (),
new \StructType\County (),
new \StructType\CountryRegion (),
new \StructType\CurrencyCode ($currencyCode),
new \StructType\CreditLimit ($creditLimit),
new \StructType\Blocked ($blocked),
new \StructType\PaymentMethodCode ($paymentMethodCode),
new \StructType\CustDiscGroup ($custDiscGroup),
new \StructType\SalespersonCode ($salespersonCode),
new \StructType\EquipeAgentCode ($equipeAgentCode),
new \StructType\LocationCode($locationCode),[...]
Logs of the SOAP server gave to me then I am trying to do this:
<ven1:Nom NomVide="$nom"></ven1:Nom>
And it is false of course...
BUT I NEED :
<ven1:Nom NomVide="">$nom</ven1:Nom>
Here is my StructType\Nom class code:
class Nom extends AbstractStructBase
{
/**
* The NomVide
* Meta information extracted from the WSDL
* - use: optional
* #var string|null
*/
protected ?string $NomVide = null;
/**
* Constructor method for Nom
* #uses Nom::setNomVide()
* #param string $nomVide
*/
public function __construct(?string $nomVide = null)
{
$this
->setNomVide($nomVide);
}
/**
* Get NomVide value
* #return string|null
*/
public function getNomVide(): ?string
{
return $this->NomVide;
}
/**
* Set NomVide value
* #param string $nomVide
* #return \StructType\Nom
*/
public function setNomVide(?string $nomVide = null): self
{
// validation for constraint: string
if (!is_null($nomVide) && !is_string($nomVide)) {
throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($nomVide, true), gettype($nomVide)), __LINE__);
}
$this->NomVide = $nomVide;
return $this;
}
}
Per example there is no problem with the value "3333", which is just a simple string type.
I have this problem with all StructType type.
If someone knows how to help me
I have finally found the solution.
In the WSDL source, there were multiple node with the same name, and in my code only one class were generated by name with WSDLtoPHP.
We asked WSDL owner to change the name of node in the WSDL and we generated new class with WSDLtoPHP librairy.
Now it is work !

php - Stripe Usage Record class not found

I'm trying to add usage records to my subscription. using the stripe create usage record endpoint (https://stripe.com/docs/api#usage_record_create).
running my function im getting an error returning saying Class 'Stripe\UsageRecord' not found in file I havent defined the namespace because I have beeen accessing it directly referencing stripe using \Stripe\ which I brought in using composer. I've tried a composer update but that didnt seem to do the trick. I'm guessing it's missing the UsageRecord.php file from the composer install but I have no clue where to add a copy of the file to the stripe package
public function stripeUsageRecord()
{
$authUser = auth()->user();
$business = $authUser['business_id'];
$user_amount = Transactions::select("user_id")
->where("business_id", "=", $business)
->groupBy("user_id")->count();
$current_time = Carbon::now()->toDateTimeString();
\Stripe\Stripe::setApiKey(env("STRIPE_SECRET"));
\Stripe\UsageRecord::create(array(
"quantity" => $user_amount,
"timestamp" => $current_time,
"subscription_item" => 'sub_DnAKVwNY2Sc4zf',
"action" => 'set'
));
}
Most likely you're using too old version of this library. Stripe\UsageRecord was introduced in version 6.6.0, so I suggest to update library to the last version:
composer require "stripe/stripe-php:^6.19"
You definitely should not modify content of vendor directory and copy&paste classes from different version of library.
Seemed like I was missing a part of the stripe package.
I found a copy of UsageRecord.php online and created the file in path vendor\stripe\stripe-php\lib\UsageRecord.php
I then added the contents of the code that I found online and added them to the file and it worked. The contents are posted below:
<?php
namespace Stripe;
/**
* Class UsageRecord
*
* #package Stripe
*
* #property string $id
* #property string $object
* #property bool $livemode
* #property int $quantity
* #property string $subscription_item
* #property int $timestamp
*/
class UsageRecord extends ApiResource
{
const OBJECT_NAME = "usage_record";
/**
* #param array|null $params
* #param array|string|null $options
*
* #return \Stripe\ApiResource The created resource.
*/
public static function create($params = null, $options = null)
{
self::_validateParams($params);
if (!array_key_exists('subscription_item', $params)) {
throw new Error\InvalidRequest("Missing subscription_item param in request", null);
}
$subscription_item = $params['subscription_item'];
$url = "/v1/subscription_items/$subscription_item/usage_records";
$request_params = $params;
unset($request_params['subscription_item']);
list($response, $opts) = static::_staticRequest('post', $url, $request_params, $options);
$obj = \Stripe\Util\Util::convertToStripeObject($response->json, $opts);
$obj->setLastResponse($response);
return $obj;
}
}

Get masterRequest URL in a fragment controller

I have made a method called by an Ajax request when a button is clicked.
/**
* #param Request $request
*
* #Route("/add", name="rapid_access_add", options={"expose"=true})
* #Method({"GET"})
*
* #return Response
*/
public function addRouteAction(Request $request)
{
$title = $request->query->get('title');
$user = $this->getUser();
$url = $this->get('request_stack')->getMasterRequest()->getUri();
$rapidAccess = new RapidAccess();
$rapidAccess->setUrl($url)
->setTitle($title)
->setUser($user);
$em = $this->getDoctrine()->getManager();
$em->persist($rapidAccess);
$em->flush();
$this->addFlash('success', $this->get('translator')->trans('user.flash.rapid_access_added', ['%title%' => $title], 'front'));
return new Response('OK');
}
I'm trying to get the URL of the current page, render by another controller (this method is in a fragment controller).
But when I use $this->get('request_stack')->getMasterRequest()->getUri(); this give me the URL of the addRouteAction method.
This should give me the master request URL but I don't understand why this send me this method URL. How can I get the current page URL instead of this method URL ?
Maybe I should get the URL with JS instead ?
Thanks
Why do use request stack ?
You can use directly Request from Controller :
$request->getUri();

Controller not found Symfony

I am a beginner in Symfony 2.8. I have a problem with my controller.
That is my controller:
class ExampleController extends ExtraController
{
/**
* #ParamConverter("site", class="Bundle:Site", converter="site_slug_converter")
* #Route("/formacion-example", name="example_web.front.example_training", requirements={"site": "es"})
*
* Render the Example form page
*
* #param Site $site
*
* #return Response
*/
public function example2TrainingFormAction(Site $site)
{
$options = ['site' => $site, 'projectId' => $this->get('example.doctrine.project_getter')->getProject()];
$form = $this->createForm(ExampleTrainingType::class, null, $options);
$viewData = ['form' => $form->createView()];
return $this->render('ExampleFrontContactFormBundle:Example:example_training.html.twig', $viewData);
}
}
When I go to my Route www.example.com/es/formacion-example symfony return to me:
HTTP status: Error 500
Controller: n/a
Route name:example_web.front.example_training
Has session: no
In symfony documentation I cant find a solution.
Thank you! :)
adding the answer here as well:
i.e. the site parameter was missing from the route
#Route("/{site}/formacion-example", ...

Secure method using annotations

I have a page with a form and want to know if it is possible to access it using GET, but only allow logged in users to POST to it.
I know this can be done in security.yml, but am not sure how to do it with annotations.
/**
* #param Request $request
* #return Response
* #Security("has_role('ROLE_USER')")
* #Method(methods={"POST"})
*/
public function calculatorAction(Request $request)
{
$form=$this->createForm(new CallRequestType(),$callReq=new CallRequest());
$form->handleRequest($request);
if($form->isValid()){
//blabla
}
return $this->render('MyBundle:Pages:calculator.html.twig', array('form' => $form));
}
This will secure the whole function, but I want to access it, just not POST to it without being logged in. An alternative would be to check if there is a logged in user in the $form->isValid() bracket. But I'm still wondering if it can be done with annotations.
You could do something like this.
You can allow both method types anonymously, and check just inside the controller to see if the user is authenticated and is POSTing.
(You don't state which version of symfony you're using, so you might have to substitute the authorization_checker (2.8) for the older security.context service)
/**
* #param Request $request
* #return Response
*
* #Route("/someroute", name="something")
* #Method(methods={"POST", "GET"})
*/
public function calculatorAction(Request $request)
{
if ( !$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY') && $request->getMethod() == 'POST') {
throw new AccessDeniedHttpException();
}
$form=$this->createForm(new CallRequestType(),$callReq=new CallRequest());
$form->handleRequest($request);
// you also need to check submitted or youll fire the validation on every run through.
if($form->isSubmitted() && $form->isValid()){
//blabla
}
return $this->render('MyBundle:Pages:calculator.html.twig', array('form' => $form));
}

Categories