I'm developping a website using symfony framework. Now I'm trying to integrate recaptcha into my form so that I used this EWZRecaptchaBundle.
I hardly could install it using the 1.* version (not the version mentioned in the documentation). I followed the documentation and get the keys from hereand I put as domain :127.0.0.1 since I'm on localhost. Then I changed my formType.php file like this:
use EWZ\Bundle\RecaptchaBundle\Validator\Constraints as Recaptcha;
class ContactType extends AbstractType
{
/**
* #Recaptcha\True
*/
public $recaptcha;
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('email')
->add('subject')
->add('message')
->add('recaptcha', 'ewz_recaptcha')
;
}
and added the recaptcha on my twig file like this:
{% form_theme form 'EWZRecaptchaBundle:Form:ewz_recaptcha_widget.html.twig' %}
{{ form_widget(form.recaptcha, { 'attr': {
'options' : {
'theme': 'light',
'type': 'image'
},
} })
}}
But when I try to display the page I get : The parameter "fr" must be defined.
Looking in the details of the error I found:
at appProdDebugProjectContainer ->getParameter ('fr')
in C:\wamp\www\fstn\vendor\excelwebzone\recaptcha-bundle\EWZ\Bundle\RecaptchaBundle\Form\Type\RecaptchaType.php at line 62 -
$this->publicKey = $container->getParameter('ewz_recaptcha.public_key');
$this->secure = $container->getParameter('ewz_recaptcha.secure');
$this->enabled = $container->getParameter('ewz_recaptcha.enabled');
$this->language = $container->getParameter($container->getParameter('ewz_recaptcha.locale_key'));
}
/**
Is it related to the version of the Recaptcha Bundle that I have installed? how can I fix this?
Try to change this line:
$this->language = $container->getParameter($container->getParameter('ewz_recaptcha.locale_key'));
to this:
$this->language = $container->getParameter('ewz_recaptcha.locale_key');
This issue should be fixed in version 2.X
Related
I just upgraded my app from Laravel v8 to v9. Now I'm having an issue with the following code throwing this error:
League\Flysystem\UnableToRetrieveMetadata : Unable to retrieve the file_size for file at location: test_file.xlsx.
My controller:
<?php
namespace App\Http\Controllers\Reports;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
class ReportDownloadController extends Controller
{
/**
* Handle the incoming request.
*
* #param string $path
* #return \Symfony\Component\HttpFoundation\StreamedResponse
*/
public function __invoke(string $path): \Symfony\Component\HttpFoundation\StreamedResponse
{
return Storage::disk('temp')->download($path, request()->query('filename'));
}
}
The relevant test:
/** #test */
public function it_returns_a_file_download_with_the_provided_filename_presented_to_the_user()
{
$this->withoutExceptionHandling();
Storage::fake('temp');
$fakeFile = UploadedFile::fake()->create('test_file.xlsx');
Storage::disk('temp')->put('test_file.xlsx', $fakeFile);
$response = $this->actingAs($this->user)
->getJson(route('reports.download', ['path' => 'test_file.xlsx', 'filename' => 'Appropriate.xlsx']));
$response->assertDownload('Appropriate.xlsx');
}
I know Flysystem was updated to v3, but I can't seem to figure out how to resolve this issue.
I even created an empty Laravel 9 app to test with the following code and still get the same error, so I don't think it is my app.
public function test_that_file_size_can_be_retrieved()
{
Storage::fake('local');
$fakeFile = UploadedFile::fake()->create('test_file.xlsx', 10);
Storage::disk('local')->put('test_file.xlsx', $fakeFile);
$this->assertEquals(10, (Storage::disk('local')->size('test_file.xlsx') / 1024));
}
What am is missing?
I've had the same problem when switching from Laravel 8 to Laravel 9.
The error Unable to retrieve the file_size was actually thrown because it couldn't find the file at all at the path provided.
In my case, it turned out that the path that was provided to the download function started with a /, which wasn't cause for problem with Flysystem 2 but apparently is with Flysystem 3.
Given the tests you're showing it doesn't look like it's the issue here but maybe this will help anyway.
So it turns out my test was broken all along. I should have been using $fakeFile->hashName() and I had the filename where I should have had '/' for the path in my Storage::put().
Here are the corrected tests that pass as expected:
/** #test */
public function it_returns_a_file_download_with_the_provided_filename_presented_to_the_user()
{
$this->withoutExceptionHandling();
Storage::fake('temp');
$fakeFile = UploadedFile::fake()->create('test_file.xlsx');
Storage::disk('temp')->put('/', $fakeFile);
$response = $this->actingAs($this->user)
->getJson(route('reports.download', ['path' => $fakeFile->hashName(), 'filename' => 'Appropriate.xlsx']));
$response->assertDownload('Appropriate.xlsx');
}
and
public function test_that_file_size_can_be_retrieved()
{
Storage::fake('local');
$fakeFile = UploadedFile::fake()->create('test_file.xlsx');
Storage::disk('local')->put('/', $fakeFile);
$this->assertEquals(0, Storage::disk('local')->size($fakeFile->hashName()));
}
Thanks, #yellaw. Your comment about it not being able to find the file at the path provided helped me realize I had done something stupid.
BotMan Version: 2.6.1
PHP Version: 8.1
Messaging Service(s): Facebook
Cache Driver: LaravelCache
Laravel: 9.18
Description:
Hi, im geting this error in laravel 9, how to handle it easiest way?
method create not exist, so should i make new class that extends Request with method create ?
I already tried to change all references from use Symfony\Component\HttpFoundation\Response;
to Illuminate\Http\Response (and Request) but this also not work.
curl -X GET "https://somedomain.org/botman?hub.verify_token=MySecretTokenFromDotENV&hub.challenge=CHALLENGE_ACCEPTED&hub.mode=subscribe"
Reponse:
Error: Call to undefined method Symfony\Component\HttpFoundation\Response::create() in file /var/www/nams/botman/driver-facebook/src/FacebookDriver.php on line 120
#0 /var/www/nams/botman/botman/src/Drivers/DriverManager.php(157): BotMan\Drivers\Facebook\FacebookDriver->verifyRequest()
#1 /var/www/nams/botman/botman/src/BotMan.php(542): BotMan\BotMan\Drivers\DriverManager::verifyServices()
#2 /var/www/nams/botman/botman/src/BotMan.php(421): BotMan\BotMan\BotMan->verifyServices()
#3 /var/www/nams/app/Http/Controllers/BotManController.php(40): BotMan\BotMan\BotMan->listen()
#4 /var/www/nams/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): App\Http\Controllers\BotManController->handle()...
Steps To Reproduce:
Install botman on laravel 9 from local repository (path)
change in composer/json dependencies to fit laravel 9
Try to connect to facebook like:
$config = [
'user_cache_time' => 720,
'config' => [
'conversation_cache_time' => 720 ,
],
// Your driver-specific configuration
'facebook' => [
'token' => env('FACEBOOK_TOKEN'),
'app_secret' => env('FACEBOOK_APP_SECRET'),
'verification' => env('FACEBOOK_VERIFICATION'),
]
];
$botman = app('botman');
DriverManager::loadDriver(\BotMan\Drivers\Facebook\FacebookDriver::class);
BotManFactory::create($config, new LaravelCache());
$botman->listen();
try to get response for facebook by:
curl -X GET "https://somedomain.org/botman?hub.verify_token=MySecretTokenFromDotENV&hub.challenge=CHALLENGE_ACCEPTED&hub.mode=subscribe"
Function that generates error is below, probably updating it to newest laravel/symfony will work, but I'm not yet so confident to know how to repair this
/**
* #param Request $request
* #return null|Response
*/
public function verifyRequest(Request $request)
{
if ($request->get('hub_mode') === 'subscribe' && $request->get('hub_verify_token') === $this->config->get('verification')) {
return Response::create($request->get('hub_challenge'))->send();
}
}
You can replace
use Symfony\Component\HttpFoundation\Response;
by
use Response; (\Illuminate\Support\Facades\Response)
And in the function do :
/**
* #param Request $request
* #return null|Response
*/
public function verifyRequest(Request $request)
{
if ($request->get('hub_mode') === 'subscribe' && $request->get('hub_verify_token') === $this->config->get('verification')) {
return Response::make($request->get('hub_challenge'))->send();
}
}
At least it worked for me on TwilioDriver
In laravel 9 app I want to add additive paramerer into Resource and looking at this
Laravel 5.6 - Pass additional parameters to API Resource?
branch I remade in app/Http/Resources/CurrencyResource.php :
<?php
namespace App\Http\Resources;
use App\Library\Services\DateFunctionalityServiceInterface;
use Illuminate\Http\Resources\Json\JsonResource;
use App;
use Illuminate\Support\Facades\File;
use Spatie\Image\Image;
use App\Http\Resources\MediaImageResource;
class CurrencyResource extends JsonResource
{
protected $show_default_image = false;
public function showDefaultImage($value){
$this->show_default_image = $value;
return $this;
}
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
*
* #return array
*/
public function toArray($request)
{
$dateFunctionality = App::make(DateFunctionalityServiceInterface::class);
$currencyImage = [];
$currencyMedia = $this->getFirstMedia(config('app.media_app_name'));
if ( ! empty($currencyMedia) and File::exists($currencyMedia->getPath())) {
$currencyImage['url'] = $currencyMedia->getUrl();
$imageInstance = Image::load($currencyMedia->getUrl());
$currencyImage['width'] = $imageInstance->getWidth();
$currencyImage['height'] = $imageInstance->getHeight();
$currencyImage['size'] = $currencyMedia->size;
$currencyImage['file_title'] = $currencyMedia->file_name;
}
else {
\Log::info( varDump($this->show_default_image, ' -1 $this->show_default_image::') );
$currencyImage['url'] = $this->show_default_image ? '/images/default-currency.jpg' : '';
}
// $currencyMedia = $currency->getFirstMedia(config('app.media_app_name'));
return [
'id' => $this->id,
'name' => $this->name,
...
and with code in control :
'currency' => (new CurrencyResource($currency))->showDefaultImage(false),
its work ok, but I got an error :
Method Illuminate\Support\Collection::showDefaultImage does not exist.
when I applyed this method for collection:
return (CurrencyResource::collection($currencies))->showDefaultImage(true);
But in link above there is a similar way :
UserResource::collection($users)->foo('bar');
What is wrong in my code and how that can be fixed ?
Thanks!
I wonder if there is a reason you can't use this approach: https://stackoverflow.com/a/51689732/8485567
Then you can simply use the request parameters to modify your response.
If you really want to get that example working in that way, it seems you are not following the example correctly.
You need to override the static collection method inside your CurrencyResource class:
public static function collection($resource){
return new CurrencyResourceCollection($resource);
}
You also need to create the CurrencyResourceCollection class and define the showDefaultImage method and $show_default_image property on that class as in the example you referred to.
Then you should be able to do:
CurrencyResource::collection($currencies)->showDefaultImage(true);
The reason the way you are doing it doesn't work is because you haven't defined the static collection method on your resource hence it's defaulting to the normal behavior of returning a default collection object as you can see in your error message.
I've been looking for a solution for a while but none of the one I find really allows me to do what I want. I would just like to create routes that don't necessarily require an entity or id to be used. Can you help me the documentation is not clear to do this.
Thank you beforehand.
As you can read in the General Design Considerations, just make an ordinary PHP class (POPO). Give it an ApiResource annontation like this:
* #ApiResource(
* collectionOperations={
* "post"
* },
* itemOperations={}
* )
Make sure the folder your class is in is in the paths list in api/config/packages/api_platform.yaml. There usually is the following configuration:
api_platform:
mapping:
paths: ['%kernel.project_dir%/src/Entity']
You should add your path if your class is not in the Entity folder.
Api Platform will expect json to be posted and try to unserialize it into an instance of your class. Make a custom DataPersister to process the instance, for example if your class is App\ApiCommand\Doit:
namespace App\DataPersister;
use ApiPlatform\Core\DataPersister\ContextAwareDataPersisterInterface;
use App\ApiCommand\Doit;
use App\ApiResult\DoitResult;
final class DoitDataPersister implements ContextAwareDataPersisterInterface
{
public function supports($data, array $context = []): bool
{
return $data instanceof Doit;
}
public function persist($data, array $context = [])
{
// code to process $data
$result = new DoitResult();
$result->description = 'Hello world';
return $result;
}
public function remove($data, array $context = [])
{
// will not be called if you have no delete operation
}
}
If you need Doctrine, add:
public function __construct(ManagerRegistry $managerRegistry)
{
$this->managerRegistry = $managerRegistry;
}
See Injecting Extensions for how to use it.
Notice that the result returned by ::persist is not an instance of Doit. If you return a Doit api platform will try to serialize that as the result of your operation. But we have marked Doit as an ApiResource so (?) api platform looks for an item operation that can retrieve it, resulting in an error "No item route associated with the type App\ApiCommand\Doit". To avoid this you can return any object that Symfonies serializer can serialize that is not an ApiResource. In the example an instance of DoitResult. Alternatively you can return an instance of Symfony\Component\HttpFoundation\Response but then you have to take care of the serialization yourself.
The post operation should already work, but the swagger docs are made from metadata. To tell api platform that it should expect a DoitResult to be returned, change the #ApiResource annotation:
* collectionOperations={
* "post"={
* "output"=DoitResult::class
* }
* },
This will the add a new type for DoitResult to the swagger docs, but the descriptions are still wrong. You can correct them using a SwaggerDecorator. Here is one for a 201 post response:
namespace App\Swagger;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final class SwaggerDecorator implements NormalizerInterface
{
private $decorated;
public function __construct(NormalizerInterface $decorated)
{
$this->decorated = $decorated;
}
public function normalize($object, string $format = null, array $context = [])
{
$summary = 'short explanation about DoitResult';
$docs = $this->decorated->normalize($object, $format, $context);
$docs['paths']['/doit']['post']['responses']['201']['description'] = 'Additional explanation about DoitResult';
$responseContent = $docs['paths']['/doit']['post']['responses']['201']['content'];
$this->setByRef($docs, $responseContent['application/ld+json']['schema']['properties']['hydra:member']['items']['$ref'],
'description', $summary);
$this->setByRef($docs, $responseContent['application/json']['schema']['items']['$ref'],
'description', $summary);
return $docs;
}
public function supportsNormalization($data, string $format = null)
{
return $this->decorated->supportsNormalization($data, $format);
}
private function setByRef(&$docs, $ref, $key, $value)
{
$pieces = explode('/', substr($ref, 2));
$sub =& $docs;
foreach ($pieces as $piece) {
$sub =& $sub[$piece];
}
$sub[$key] = $value;
}
}
To configure the service add the following to api/config/services.yaml:
'App\Swagger\SwaggerDecorator':
decorates: 'api_platform.swagger.normalizer.api_gateway'
arguments: [ '#App\Swagger\SwaggerDecorator.inner' ]
autoconfigure: false
If your post operation is not actually creating something you may not like the 201 response. You can change that by specifying the response code in the #ApiResource annotation, for example:
* collectionOperations={
* "post"={
* "output"=DoitResult::class,
* "status"=200
* }
* },
You may want to adapt the SwaggerDecorator accordingly.
Creating a "get" collection operation is similar, but you need to make a DataProvider instead of a DataPersister. The chapter9-api branch of my tutorial contains an example of a SwaggerDecorator for a collection response.
Thanks you for answer. I had some information but not everything. I will try the weekend.
On my project i made a contact form. It was store details on databse and shows admin panel and sends it to via mail so i cant pass array variables to mailable view.
My controller;
$iletisim = new Contact();
$iletisim->ad = $request->input('ad');
$iletisim->soyad =$request->input('soyad');
$iletisim->email = $request->input('email');
$iletisim->mesaj = $request->input('mesaj');
$iletisim->save();
$gonder = array( 'gonderen'=>$request->input('ad'),
'email'=>$request->input('email'),
'mesaj'=>$request->input('mesaj')
);
Mail::send(new ContactMail($gonder));
Session::flash('success', 'Mesajınız Gönderilmiştir. En kısa sürede dönüş sağlanacaktır.');
return back();
}
My Contact.php
public $bilgiler;
public function __construct($gonder)
{
$this->bilgiler = $gonder;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('homepage.emails.contact')->with(['bilgiler'=>$this->bilgiler]);
}
and my blade file
#component('mail::message')
# New Contact Form
{{$bilgiler->ad}}
Thanks,<br>
{{ config('app.name') }}
#endcomponent
Where is my mistake can you help.
Thanks
First of all, you don't need to add ->with(['bilgiler'=>$this->bilgiler]); since $bilgiger is public property. All public properties of Mailable are available in Blade
Also, since it's an array, you need to access it with:
$bilgiger['gonderen']
The $bilgiler->gonderen syntax is for objects, not for arrays. Also, you don't have id in the array.
And the last thing is you're using markdown email, so use the markdown() method:
return $this->markdown('homepage.emails.contact');