Catch Duplicate Key Error in Wordpress - wordpress

I have this code and I want to add duplication error catch in it, how can I?
if (!$row_id) {
// insert a new
if ($wpdb->insert($table_name, $args)) {
return $wpdb->insert_id;
}
} else {
// do update method here
if ($wpdb->update($table_name, $args, array('id' => $row_id))) {
return $row_id;
}
}

Related

woocommerce_order_status_completed has no data

I have created a webhook for woocommerce_order_status_completed, this hook is successfully triggered when an order is completed.
The problem is I do not get any data from the order completed other than its ID. the response shows as the following.
{"action":"woocommerce_order_status_completed","arg":1640}
I made a plugin with this code that solved the issue :
function set_resource_for_webhook_payload_by_webhook_id($target_webhook_id,
$desired_resource) {
add_filter('woocommerce_webhook_resource', function($resource, $webhook_id) use
($target_webhook_id, $desired_resource) {
if($webhook_id == $target_webhook_id) {
return $desired_resource;
}
return $resource;
}, 10, 2);
add_filter('woocommerce_valid_webhook_events', function($valid_events) use ($target_webhook_id) {
try {
$topic = wc_get_webhook($target_webhook_id)->get_topic();
list($resource, $event) = explode('.', $topic);
if(!empty($event)) {
$valid_events[] = $event;
}
return $valid_events;
} catch (Exception $e) {
return $valid_events;
}
}, 10);
}
//Replace number (3) bellow with your webhook ID:
add_action('init', function(){
set_resource_for_webhook_payload_by_webhook_id(3, 'order');
});
Hope it helps anyone.

Symfony ignore 404 status code for get request

I have an application which allows users to create wishes. I use the title of each wish to make an api request to unsplash to download a picture. I now have the problem, that a user can enter a title which doesnt return any images from unsplash. In this case I'd like to use a placeholder image but my code stops after getting an 404 error. Is there a way to ignore this error and just continue my loop?
public function fetchImagesFromUnsplash() {
$wishes = $this->repository->findAll();
foreach ($wishes as $wish) {
try {
$response = $this->httpClient->request('GET', 'https://api.unsplash.com/photos/random', [
'query' => [
'query' => $wish->getDescription(),
'client_id' => 'oa1DsGebE8ehCV9SrvcA1mCx-2QfvnufUKgsIY5N0Mk'
]
]);
} catch (TransportExceptionInterface $e) {
}
if ($response) {
$data = $response->getContent();
$data = json_decode($data, true);
$imageLink = $data['urls']['raw'];
$rawImage = file_get_contents($imageLink);
if ($rawImage) {
file_put_contents("public/images/" . sprintf('imageWish%d.jpg', $wish->getId()), $rawImage);
$wish->setImagePath(sprintf('public/images/imageWish%d.jpg', $wish->getId()));
} else {
$wish->setImagePath('placeholder.png');
}
$this->em->flush();
}
}
}
EDIT:
I tried this:
public function fetchImagesFromUnsplash() {
$wishes = $this->repository->findAll();
foreach ($wishes as $wish) {
try {
$response = $this->httpClient->request('GET', 'https://api.unsplash.com/photos/random', [
'query' => [
'query' => $wish->getDescription(),
'client_id' => 'oa1DsGebE8ehCV9SrvcA1mCx-2QfvnufUKgsIY5N0Mk'
]
]);
} catch (NotFoundHttpException $e) {
}
if ($response) {
$data = $response->getContent();
$data = json_decode($data, true);
$imageLink = $data['urls']['raw'];
$rawImage = file_get_contents($imageLink);
if ($rawImage) {
file_put_contents("public/images/" . sprintf('imageWish%d.jpg', $wish->getId()), $rawImage);
$wish->setImagePath(sprintf('public/images/imageWish%d.jpg', $wish->getId()));
} else {
$wish->setImagePath('placeholder.png');
}
}
}
$this->em->flush();
}
but it still stops after the first 404
As per the documentation:
When the HTTP status code of the response is in the 300-599 range
(i.e. 3xx, 4xx or 5xx) your code is expected to handle it. If you
don't do that, the getHeaders() and getContent() methods throw an
appropriate exception
You have to check the $response->getStatusCode(), or prepare to handle a ClientException (representing 4xx status codes).

Running await inside RxJS Observable flatMap

I am trying to return an observable inside an async arrow function passed to a flatMap, but the returned observable is not being called.
protected buildUseCaseObservable(params: LoginUserParams): Observable<Session> {
return this.userRepository.getUserByName(params.getUsername())
.pipe(flatMap(async user => {
if (!user) {
throw new Error(Errors.USER_DOESNT_EXIST);
}
const match = await this.cypher.compare(params.getPassword(), user.password);
if (!match) {
throw new Error(Errors.WRONG_PASSWORD);
}
return Observable.create((subscriber: Subscriber<Session>) => {
subscriber.next(new Session("token test", "refreshToken test"));
subscriber.complete();
});
}));
}
Does anyone knows why does it happen and how can I solve it? Thanks in advance.
Solved, I just turned the promise into an observable and did flatMap it.
protected buildUseCaseObservable(params: LoginUserParams): Observable<Session> {
return this.userRepository.getUserByName(params.getUsername())
.pipe(flatMap(storedUser => {
if (!storedUser) {
throw new Error(Errors.USER_DOESNT_EXIST);
}
return from(this.cypher.compare(params.getPassword(), storedUser.password));
})).pipe(flatMap(match => {
if (!match) {
throw new Error(Errors.WRONG_PASSWORD);
}
return Observable.create((subscriber: Subscriber<Session>) => {
subscriber.next(new Session("token test", "refreshToken test"));
subscriber.complete();
});
}));
}

How to set session variable in header file in laravel

I am having problem to get session variable in header file. In my controller i have this code for login.
public function login(Request $request)
{
$inputs = $request->only('email', 'password');
//dd($request->input('email'));
$rules = array(
'email' =>'required',
'password' => 'required'
);
$validator = Validator::make($inputs, $rules);
if ($validator->fails()){
$messages = $validator->messages();
return redirect('login')
->withErrors($validator)
->withInput($request->except('password'));
} else {
if (auth()->attempt($inputs)) {
$is_admin = DB::table('users')
->where('email', $request->input('email'))
->first();
if ($is_admin->is_admin == 1) {
return redirect('/company_details');
} elseif ($is_admin->is_admin == 2) {
return redirect('dashboard');
} else {
dd('something wrong');
}
} else {
return redirect('login')->withErrors(['error' => 'Email or password donot match']);
}
}
}
I have a login form which in which my header file is include, and i have to get session variable in my header file. Like if a user is logged in, username or email should appear in place of login button.
Anyone please help me for this.
use Illuminate\Support\Facades\Session;
or
use Session
Set Session Variable
Session::Flash('message_key', 'Your Message');
return redirect('/yourmsgpage')
Show the session output
#if(Session::has('message_key'))
<div>
{{ Session::get('message_key' }}
</div>
#endif
Try this to get user session id
Auth::user()->id

How to pass an element in Crawler each function?

I parse my xml with Symfony's Crawler and cannot get how can I pass (other words continue) an element and not to include it into final array?
For example:
$node->filterXPath('//ExampleNode')->each(function(Crawler $child, $i) {
if (! count($child->filterXPath('//ChildNode'))) {
continue;
}
return $child->filterXPath('//ChildNode')->text();
});
You can use the Symfony\Component\DomCrawler\Crawler::reduce(Closure)
$crawler->reduce(function($result, $item) {
$childNodes = $item->filterXPath('//ChildNode');
if ($childNodes->count()) {
$result[] = $item;
}
});

Resources