Lumen 5.5 Socialite Providers doesn't works with setConfig() - php

I use Laravel Socialite Providers (https://socialiteproviders.github.io/) to login user on Lumen 5.5 API.
setConfig() method, to force config, doesn't works for me...
Here below, my error and my code. The problem is that I do not know why I have this error.
Display Error:
Type error: Argument 1 passed to
Laravel\Socialite\SocialiteManager::formatConfig() must be of the type
array, null given, called in
/home/vagrant/www/project1/api.website.app/vendor/laravel/socialite/src/SocialiteManager.php
on line 125
PHP code:
$clientId = env('TWITTER_KEY');
$clientSecret = env('TWITTER_SECRET');
$redirectUrl = env('TWITTER_REDIRECT_URI');
$additionalProviderConfig = [];
$config = new SocialiteConfig($clientId, $clientSecret, $redirectUrl, $additionalProviderConfig);
return Socialite::with('twitter')->stateless()->setConfig($config)->redirect();

You need to configure services configuration first! Create a services.php file inside config folder (you may create this one if you don't have it already).
File services.php
return [
'twitter' => [
'client_id' => env('TWITTER_KEY'),
'client_secret' => env('TWITTER_SECRET'),
'redirect' => env('TWITTER_REDIRECT_URI'),
]
];
Your code should be like this:
use Laravel\Socialite\Facades\Socialite;
// You may not this one, read below explanation
app()->configure('services');
return Socialite::with('twitter')->stateless()->redirect();
It is better if you move the configure line to bootstrap/app.php file:
// Just right before register SocialiteProvider
$app->configure('services');
$app->register(SocialiteProviders\Manager\ServiceProvider::class);
If you have moved this configure, your code now should be:
use Laravel\Socialite\Facades\Socialite;
return Socialite::with('twitter')->stateless()->redirect();
PS:
If you have call to undefined stateless method, it means you don't set the listener yet, you can read here. Open your App\Providers\EventServiceProvider, add this line:
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
'SocialiteProviders\Manager\SocialiteWasCalled' => [
'SocialiteProviders\Twitter\TwitterExtendSocialite#handle',
]
];
}
And don't forget to add this line to your bootstrap/app.php file:
$app->register(App\Providers\EventServiceProvider::class);

Related

How do I pass a registered service singleton into another registered service's constructor in Laravel 7?

I have recently been learning about the AppServiceProvider. I have registered a service in the AppServiceProvider which creates a singleton - an instantiated GuzzleHttp Client, like so:
$this->app->singleton('GuzzleHttp\Client', function($api) {
return new Client([
'base_uri' => env('ELASTICSEARCH_HOST'),
'auth' => [
env('ELASTICSEARCH_USER'),
env('ELASTICSEARCH_PASS')
],
]);
});
This is connecting to an ElasticSearch API, and that currently works:
$response = app('GuzzleHttp\Client')->request('GET');
I have set up a facade called ElasticSearchFacade, which contains only the getFacadeAccessor():
protected static function getFacadeAccessor()
{
return 'elasticSearch';
}
I have also registered elasticSearch in my AppServiceProvider, like so:
$this->app->bind('elasticSearch', function() {
return new ElasticSearch();
});
This creates a new ElasticSearch instance. However, I would love to pass the GuzzleHttp\Client into the elasticSearch service. So I have tried adding the following to my ElasticSearch.php file:
use GuzzleHttp\Client;
class ElasticSearch
{
protected $client;
public function __contruct(Client $client)
{
$this->client = $client;
}
public function handle()
{
$response = $this->client->request('GET');
die($response->getBody()->getContents());
}
}
I have now changed the registered service to pass through the GuzzleHttp Client like so:
$this->app->bind('elasticSearch', function() {
return new ElasticSearch(app('GuzzleHttp\Client'));
});
However I am getting the error:
PHP Error: Call to a member function request() on null
The constructor method is __construct not __contruct. You have not defined a custom constructor for your ElasticSearch class. So that member variable is null.
Side Note: do not call env outside of the configuration files.
To avoid having to make these env calls outside of configuration files you can just add configuration files as needed or add to current configuration files. Something like Elastic Search credentials can probably get added to the services.php configuration file:
<?php
return [
...
'elasticsearch' => [
'host' => env('ELASTICSEARCH_HOST'),
'user' => env('ELASTICSEARCH_USER'),
'password' => env('ELASTICSEARCH_PASS'),
],
...
];
Now that you have these in the configuration you can use the configuration system to pull these values:
config('services.elasticsearch'); // that whole array of values
config('services.elasticsearch.host'); // just that host value
Config::get('services.elasticsearch');
app('config')->get(...);
There are multiple ways to access the configuration system.

Laravel logging.channels.single.path with queue is cached?

Im using Queue::before in AppServiceProvider.php and set logging.channels.single.path value every time when job started:
config(['logging.channels.single.path' => storage_path('logs/accounts/'.$command->acc->login.'.log')]);
When I running 1 job all ok - logs in the right place.
When running 2 or more it writing logs to different files - one account can write to another accounts logfile. Why is it happening? It looks like it is caching the config variable.
Queue on horizon redis. One job after done dispatching another same job with the same $acc instance.
Queue::before(function (JobProcessing $event) {
$job = $event->job->payload();
$command = unserialize($job['data']['command']);
Added ^^^ from where $command going.
Customization is now done through invoking a custom formatter for Monolog.
This can be setup in config/logging.php, note the non-default tap parameter:
'channels' => [
'daily' => [
'driver' => 'daily',
'tap' => [App\Logging\CustomFilenames::class],
'path' => storage_path('logs/accounts/laravel.log'),
'level' => 'debug',
],
]
In your custom formatter, you can manipulate the Monolog logger however you wish:
<?php
namespace App\Logging;
use Monolog\Handler\RotatingFileHandler;
class CustomFilenames
{
/**
* Customize the given logger instance.
*
* #param \Illuminate\Log\Logger $logger
* #return void
*/
public function __invoke($logger) {
foreach ($logger->getHandlers() as $handler) {
if ($handler instanceof RotatingFileHandler) {
$login = $command->acc->login;
$handler->setFilenameFormat("{filename}-$login-{date}", 'Y-m-d');
}
}
}
}
See: https://laravel.com/docs/5.6/logging#advanced-monolog-channel-customization
https://github.com/Seldaek/monolog/blob/master/src/Monolog/Handler/RotatingFileHandler.php
The configuration values work globaly for all sessions, like global variables (
See the exampe here https://laravel.io/forum/how-can-i-set-global-dynamic-variables-in-laravel)
You set the value in the config file always to the last login. Therefore all new logs go in the new named config file.

Elastic search configurations not working in laravel v5.3

I have setup new laravel v5.3 project and install elastic search driver to implement elastic search via composer. But when I reload my page then I always receive This page isn’t working even the elastic search is running on my system below is my complete code that I code.
composer.json
"require": {
"php": ">=5.6.4",
"elasticsearch/elasticsearch": "^6.0",
"laravel/framework": "5.3.*"
},
web.php
Route::get('/',array('uses' => 'ElasticSearch#addPeopleList'));
Controller
<?php
namespace App\Http\Controllers;
class ElasticSearch extends Controller
{
// elastic
protected $elastic;
//elastic cliend
protected $client;
public function __construct(Client $client)
{
$this->client = ClientBuilder::create()->build();
$config = [
'host' =>'localhost',
'port' =>9200,
'index' =>'people',
];
$this->elastic = new ElasticClient($config);
}
public function addPeopleList(){
echo "<pre>";
print_r($this->$elastic);
exit;
}
}
But when I refresh the page then This page isn’t working i received this message and page not loaded one thing that I want to let you know that I made no changes in app.php file of configuration. Please eduacate to solve this issue.
if You want to instantiate an elastic client with some configuration, You should use method ClientBuilder::fromConfig(array $config).
In your case it should be
<?php
$client = ClientBuilder::fromConfig([
'hosts' => [ 'localhost:9200' ]
]);
As You can notice above hosts must be provided as array.
Also I'm not sure that Elasticsearch client that You use have ElasticClient class.
Also if You provided actual code from your controller than it contains an error. You should call class properties like that: print_r($this->client) (without $ near the property name).
Finaly your controller should looks like this:
<?php
namespace App\Http\Controllers;
use Elasticsearch\ClientBuilder;
class ElasticSearch extends Controller
{
/**
* #var \Elasticsearch\Client
*/
protected $client;
public function __construct()
{
$this->client = ClientBuilder::fromConfig([
'hosts' => [
'localhost:9200',
],
]);
}
public function addPeopleList(){
echo "<pre>";
print_r($this->client);
exit;
}
}
And to add a document to the index You need to call this command according to the official documentation
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 'my_id',
'body' => ['testField' => 'abc']
];
$response = $client->index($params);
print_r($response);
Official documentation can be found here https://github.com/elastic/elasticsearch-php
P.S. Sorry for my English. It is far from perfect.

Laravel Firebase Data Sync Fail

Integrating Firebase in "RESTFUL API" for the first time. The data had to sync into two databases i.e. MySQL and Firebase but the data didn't sync in Firebase.
Installation of firebase sync trait
composer require mpociot/laravel-firebase-sync
The configuration code to integrate Firebase into my API :-
'firebase' => [
'api_key' => 'AIzaSyCbOasfdsfdsfds',
'auth_domain' => 'restasdsaful-asdfs.firebaseapp.com',
'projectId' => 'restful-23aasdfsf60',
'messagingSenderId' => '8445794551330',
'database_url' => 'https://restful-sdfsdf23a60.firebaseio.com',
'secret' => 'mZ93YRkZ9ZErQvvtJyFKmRopsdfcwUEE5ImoMW89hWB',
'storage_bucket' => 'restfulas-23a60asda.appspot.com',
],
Note: for security reason I have changed values of configuration attributes.
Path where Firebase had been configured. config/services.php
The process that I applied for Syncronizing the Model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Mpociot\Firebase\SyncsWithFirebase;
class Demo extends Model
{
use SyncsWithFirebase;
protected $fillable = ['task','is_done'];
protected $visible = ['id', 'task', 'is_done'];
}
Please suggest a solution if there's any error in my code or any alternatives for this kind of problem. Thanks in Advance!!.
You can do like this:
use Firebase\Firebase;
class FirebaseController extends Controller
{
public function storeTask(Request $request){
$FIREBASE_URL = 'your_url_key;
$FIREBASE_SECRET = 'your_firebase_secret_key';
$fb = Firebase::initialize($FIREBASE_URL, $FIREBASE_SECRET);
$fb = new Firebase([ 'base_url' => $FIREBASE_URL, 'token' => $FIREBASE_SECRET,]);
$nodeSetContent = $fb->push('msg', $request->all());
return response()->json(['data'=>$nodeSetContent]);
}
}
you can take reference from this link (https://github.com/eelkevdbos/firebase-php)

How to configure middleware in DI in Slim 3

I want to configure several middleware in Dependency Container in Slim, so that I can set several constants in a same place and add middleware in a ease.
E.G.
$configuration = [
'settings' => [
'displayErrorDetails' => true,
],
'auth_settings' => [
'serect' => 'garyAPIserver',
],
];
$container = new Slim\Container($configuration);
$container['auth'] = function ($c) {
return new AuthMiddleware($c['auth_settings']);
};
$app = new Slim\App($container);
And I try to invoke the middleware in DI:
$app->add($app->get('auth'));
And I got the warning message print by php:
Warning: Missing argument 2 for Slim\App::get(), called in E:\www\slimServer-3.0\index.php on line 12 and defined in E:\www\slimServer-3.0\vendor\slim\slim\Slim\App.php on line 146
And the error message print by Slim:
Type: RuntimeException
Message: is not resolvable
File: E:\www\slimServer-3.0\vendor\slim\slim\Slim\CallableResolver.php
Line: 82
I am new in Slim, there it possible to set middleware in DI? Is there any guides with the similar scenario?
You can do it using the $container variable:
$app->add($container->get('auth'));
Then you can use it in your router functions using:
$auth = $this->get('auth');
Take a look here for more information.

Categories