Laravel 5.5 Geocoder - php

I wanted to use this package for geocoding in Laravel. I have added it to providers and published the config, but I am getting trouble setting it up to work.
try {
$location = Geocoder::geocode('68.145.37.34')->get();
return $location;
} catch (\Exception $e) {
return $e;
}
This returns empty object.
I have left the config file as is.
return [
'cache-duration' => 9999999,
'providers' => [
Chain::class => [
GoogleMaps::class => [
'en-US',
env('GOOGLE_MAPS_API_KEY'),
],
GeoPlugin::class => [],
],
],
'adapter' => Client::class,
];
And added valid API key to env. Is there something I'm missing?
Geocoder is imported as use Geocoder\Laravel\Facades\Geocoder;
EDIT
In case someone gets to the same problem...this is how you'd get the country from it:
app('geocoder')->geocode('5.43.168.58')->get()->first()->getCountry()->getName();
Really complicated unnecessarily in my opinion, I requested a documentation change on official repo.

did you try using dd() in tinker?? I have been try it...and it work for me..
try this :
dd(app('geocoder')->geocode('68.145.37.34')->get());
response :
Illuminate\Support\Collection {#764
items: array:1 [
0 => Geocoder\Model\Address {#753
-coordinates: Geocoder\Model\Coordinates {#755
-latitude: 51.0823
-longitude: -113.9578
}
-bounds: null
-streetNumber: null
-streetName: null
-subLocality: null
-locality: "Calgary"
-postalCode: null
-adminLevels: Geocoder\Model\AdminLevelCollection {#767
-adminLevels: array:1 [
1 => Geocoder\Model\AdminLevel {#768
-level: 1
-name: "Alberta"
-code: "AB"
}
]
}
-country: Geocoder\Model\Country {#769
-name: "Canada"
-code: "CA"
}
-timezone: null
-providedBy: "geo_plugin"
}
]
}

Related

Symfony unit testing with loginUser(), login not working (returning 302 to login page)

I'm building a test for a Symfony 5.4 application.
I have created a test like this:
public function testCreateProduct() {
$client = static::createClient();
/** #var User $mainAdmin */
$mainAdmin = static::getContainer()->get(UserRepository::class)->find(1);
//$client->catchExceptions(false);
$client->loginUser($mainAdmin);
$crawler = $client->request('GET', '/en/product/new');
$this->assertResponseIsSuccessful();
$this->assertSelectorTextContains('span.username', $mainAdmin->getUsername());
}
But the login is not working, I get a 302 redirect to the login page, and if I set catchExceptions(false) I get an AccessDeniedException.
How can I debug this?
Edit:
I tried to change the patch to a public route, then I did a dd($this->getUser(), $request)
getUser() is null, but the request session contains the user:
#session: Symfony\Component\HttpFoundation\Session\Session {#16616
#storage: Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage {#16631
-savePath: "C:\www\project\var\cache\test/sessions"
#id: "a9d00704e1a0211d06ebddadfaabbf0188e9d65d94faac05afbdc63bb9fb7caa"
#name: "MOCKSESSID"
#started: true
#closed: false
#data: array:3 [
"_sf2_attributes" => &1 array:1 [
"_security_main" => "O:52:"Symfony\Bundle\FrameworkBundle\Test\TestBrowserToken":2:{i:0;s:4:"main";i:1;a:5:{i:0;C:15:"App\Entity\User":118:{a:5:{i:0;i:2;i:1;s:5:"admin";i:2;s:60:"$2y$13$abcdefghi......";i:3;i:1;i:4;b:0;}}i:1;b:1;i:2;N;i:3;a:0:{}i:4;a:9:{i:0;s:9:"ROLE_USER";i:1;s:10:"ROLE_ADMIN";i:2;[...]}}}"
]
"_sf2_meta" => &2 array:3 [
"u" => 1645718565
"c" => 1645718565
"l" => 0
]
"_symfony_flashes" => &3 []
]
I see a difference between
$request->getSession()->getBag('attributes')
done in dev (working) vs in test: in dev I have _security_secured_area, while in test I have _security_main. May this be the reason?
Solved.
Since I was using a custom firewall name in security.yaml, in my case secured_area, I had to pass that as the second parameter of loginUser():
$client->loginUser($mainAdmin, 'secured_area');

MongoDb fetch document subset using PHP

I have a MongoDB document structure like this:
[
{
"locale":"en",
"translations":[
{
"name":"translation1",
"value":"enValue"
},
{
"name":"translation2",
"value":"enValue"
},
{
"name":"translation3",
"value":"enValue"
}
]
},
{
"locale":"ru",
"translations":[
{
"name":"translation1",
"value":"ruValue"
},
{
"name":"translation2",
"value":"ruValue"
},
{
"name":"translation3",
"value":"ruValue"
}
]
}
]
and I need to get the translation with name translation1 for locale en.
The expected result I want is:
{
"_id" : ObjectId("5e845ba1005e625a6237d2e0"),
"translations" : [
{
"name" : "translation1",
"value" : "enValue"
}
]
}
I know how to do this with pure mongo, it should be like this:
db.translations.find({"locale" : "en"},
{ translations: { $elemMatch: { name: "translation1" } } } )
Here is the proof https://gyazo.com/fb9b1a505a898c7137ece5304d715171
but I can't make it work with PHP. I tried code like:
$collection = $this->database->{$group};
$collection->find(
[
'locale' => 'en',
'translations' => ['$elemMatch' => ['name' => 'translation1']
]
);
And Im getting all translations for en instead of only tranlsation1 as a result:
{
"_id" : ObjectId("5e845ba1005e625a6237d2e0"),
"locale" : "en",
"translations" : [
{
"name" : "translation1",
"value" : "enValue"
},
{
"name":"translation2",
"value":"enValue"
},
{
"name":"translation3",
"value":"enValue"
}
]
}
I tried as:
$collection = $this->database->{$group};
$collection->find(
['locale' => 'en'],
[
'translations' => ['$elemMatch' => ['name' => 'translation1']
]
);
also result is the same as above.
Tried like:
$collection = $this->database->{$group};
$collection->find(
[
'locale' => 'en',
[
'translations' => ['$elemMatch' => ['name' => 'translation1']
]
]
);
result is null
As a workaround, for now, I filter result on PHP side, but it extra work
This appears to be a bug in the driver.
This database command should be equivalent to the find you were running, but the command works as expected while the find does not.
$this->$database->command([
'find'=>'CollectionName',
'filter'=>['locale' => 'en'],
'projection'=>['translations' => ['$elemMatch' => ['name' => 'translation1']]]
])

How do I correct this one line PHP syntax?

newbie here. I have the following PHP-code for a script with Betfair-API.
if ($event->marketName == "Match Odds") {
// print_r($event);
$params = [
"marketIds" => [$event->marketId],
'priceProjection' => ['priceData' => ['EX_BEST_OFFERS']]
];
}
I need to add virtual bets. API-documentation says:
You can return virtual bets in the response when using API-NG by including the virtualise":"true" in the listMarketBook request e.g.
[
{
"jsonrpc":"2.0",
"method":"SportsAPING/v1.0/listMarketBook",
"params":{
"marketIds":[
"1.114101556"
],
"priceProjection":{
"priceData":[
"EX_BEST_OFFERS"
],
"virtualise":"true"
}
},
"id":1
}
]
How can I change my code to work? I've tried a few dozen combinations, but no luck. Sorry for being newbie.
David
$params = [
"marketIds" => [$event->marketId],
'priceProjection' => ['priceData' => ['EX_BEST_OFFERS']],
'virtualise' => true,
];

Laravel Validation – Date Format m/y Not Accepting Specific Value

I've got the following validation rules for basic authentication of a Payment Method (advanced things, like CVD validation, existing card, etc. is handled afterward by Moneris).
$rules = [
"type" => "required|in:visa,mastercard",
"nickname" => "required",
"credit_card_number" => "required|numeric|digits:16",
"expiry" => "required|string|size:5|date_format:m/y|after:today",
"cvd" => "required|numeric|digits:3"
];
The rule expiry is not accepting a specific value, 04/yy, but it is accepting 03/yy and 05/yy; I have no idea why this is happening, but I need it remedied. Has anyone come across this behaviour?
For reference, the result dd($request->input(), $validator->passes(), $validator->errors()); when I pass 04/19 is as follows:
array:6 [▼
"type" => "visa"
"nickname" => "Testing"
"credit_card_number" => "4242424242424242"
"expiry" => "04/19"
"cvd" => "123"
"masked_pan" => "************4242"
]
false
MessageBag {#502 ▼
#messages: array:1 [▼
"expiry" => array:1 [▼
0 => "The expiry does not match the format m/y."
]
]
#format: ":message"
}
When I send 05/19, everything works fine:
array:6 [▼
"type" => "visa"
"nickname" => "Testing"
"credit_card_number" => "4242424242424242"
"expiry" => "05/19"
"cvd" => "123"
"masked_pan" => "************4242"
]
true
MessageBag {#502 ▼
#messages: []
#format: ":message"
}
Looks like it's an issue with how this validation rule works in Laravel 5.4. To fix, I check the date validity of the input prepended with 01/, and if it is valid, merge that into the request, with endOfMonth() to handle after:today validation:
$mergeDate = null;
$rawInput = $request->input("expiry");
try {
$mergeDate = Carbon::createFromFormat("d/m/y", "01/".$request->input("expiry"))->endOfMonth();
} catch(\Exception $ex){}
$request->merge([
"masked_pan" => str_repeat("*", 12).substr($request->input("credit_card_number", ""), -4),
"expiry" => $mergeDate ? $mergeDate->format("d/m/y") : $request->input("expiry")
]);
So now, if I pass 04/22, it will check if 01/04/22 is valid, then convert to end of month 30/04/22, then replace that as the value passed to the validation (which also needs to be updated)
"expiry" => "required|string|size:8|date_format:d/m/y|after:today",
I also have to update and pass $messages to avoid confusion to the user:
$messages = [
"expiry.size" => "The :attribute filed must be 5 characters.",
"expiry.date_format" => "The :attribute field does not match the format m/y"
];
$validator = \Validator::make($request->all(), $rules, $messages);
And finally, replace the value with the raw input if there's an error (so the user doesn't see a value they didn't enter)
if(!$validator->passes()){
$request->merge(["expiry" => $rawInput]);
return back()->withErrors($validator)->withInput();
}
A whole bunch of nonsense, but seems to handle 04/22 and other dates just fine.

How to do an aggregate query on an embedded document?

I am using jenssegers/laravel-mongodb library in a laravel application however I need to show counts of an embedded document. Using a generic example of comment/posts, while I can solve my problem by just pulling all the posts and looping through to get comments to count them but was just was not sure if I could query them.
I did set up my relationships. In my post class I did:
public function comments()
{
return $this->hasMany('App\Comment');
}
and in my comment class:
public function post()
{
return $this->belongsTo('App\Post');
}
Later in code:
$post->comments()->save($comment);
$comment->post()->associate($post);
my document structure:
"posts" : [
{
"_id" : ObjectId("5805a11e2594ee26543ea041"),
"Post_Num" : "166236001010",
"updated_at" : ISODate("2016-10-18T04:12:14.454Z"),
"created_at" : ISODate("2016-10-18T04:12:14.451Z"),
"comments" : [
{
"Comment_Num" : "3333333",
"_id" : ObjectId("5805a11e2594ee26543ea042"),
"post_id" : "5805a11e2594ee26543ea041",
},
{
"Comment_Num" : "3333333",
"_id" : ObjectId("5805a11e2594ee26543ea042"),
"post_id" : "5805a11e2594ee26543ea041",
}
]
},
{
"_id" : ObjectId("5805a11e2594ee26543ea041"),
"Post_Num" : "166236001010",
"comments" : [
{
"Comment_Num" : "3333333",
"_id" : ObjectId("5805a11e2594ee26543ea042"),
"post_id" : "5805a11e2594ee26543ea041",
}
]
}
]
Now when I try getting the comments like:
$post->comments()->count()
or
$post->comments()->get()->count()
or
$post->comments->get()->count()
I get a 0. The same logic works if it is not an embedded document but just was wondering if it was possible to do an aggregate query ? Perhaps is best to just let the code iterate and add everything?
As you can tell I need some minor hand holding. Thank You
UPDATE: I am trying the following
public function commentCount()
{
$commentsCount = Post::raw(function($collection)
{
return $collection->aggregate(['$project' => ['_id' => 1,
'comments_count' => ['$size' => '$comments']],
['$group' => ['_id' => null, 'count' => ['$sum' => '$comments_count']]]]);
});
return $commentsCount;
}
What I get now is:
$pipeline is not a list (unexpected index: "$project")
Just to be clear, you want a list of your posts with the number of comments on each post?
Aggregation has something to offer for that:
https://docs.mongodb.com/manual/reference/operator/aggregation/size/#exp._S_size
I'm not a php dev but this is my shot at it:
Post::raw()->aggregate(
['$project' => ['_id' => 1,
'Post_Num' => 1,
'comments_count' => ['$size' => '$comments']],
['$group' => ['_id' => null, 'count' => ['$sum' => '$comments_count']]]
]);

Categories