Laravel: php match does not seem to be working - php

I'm working on a Laravel app. I've created an enum like this:
<?php
namespace Domain\Order\Enums;
use Domain\Order\Models\Order;
enum OrderStatuses : string
{
case New = 'new';
case Pending = 'pending';
case Canceled = 'canceled';
case Paid = 'paid';
case PaymentFailed = 'payment-failed';
public function createOrderStatus(Order $order) : OrderStatus
{
return match($this) {
OrderStatuses::Pending => new PendingOrderStatus($order),
OrderStatuses::Canceled => new CanceledOrderStatus($order),
OrderStatuses::Paid => new PaidOrderStatus($order),
OrderStatuses::PaymentFailed => new PaymentFailedOrderStatus($order),
default => new NewOrderStatus($order)
};
}
}
In my order model I've got the following attribute:
protected function status(): Attribute
{
return new Attribute(
get: fn(string $value) =>
OrderStatuses::from($value)->createOrderStatus($this),
);
}
which as you can see receives some data and returns an Order status.
Now, I've got the following piece of code:
$order = Order::find($orderID);
$newOrder = match ($order->status) {
OrderStatuses::New => (new NewToPaidTransition)->execute($order),
NewOrderStatus::class => (new NewToPaidTransition)->execute($order),
'new' => (new NewToPaidTransition)->execute($order),
default => null,
};
but the value of $newOrder is always null, meaning the status is not being matched to any of the elements. There should be one single element there: NewOrderStatus::class, I just added the others for debugging purposes.
If I inspect the value of $order->status while running the debugger I'm getting that it is of type Domain\Order\Enums\NewOrderStatus so why it is not being matched?
Thanks

It looks like you are testing for equality between an instance of a class and a string of the class name.
Try
$newOrder = match (get_class($order->status)) {
OrderStatuses::New => (new NewToPaidTransition)->execute($order),
NewOrderStatus::class => (new NewToPaidTransition)->execute($order),
'new' => (new NewToPaidTransition)->execute($order),
default => null,
};

Related

Product Variants Data updated with last record Every time in Laravel 5.3

I'm trying to update my products with dynamic variants. There is no issue in adding or deleting but when I trying to update, every time it updates with the last record on every field.
I'm trying to update dynamic variants where I have inserted...
color - red
shape -square
It's about dynamic form-fields, inserts work properly but when I am trying to update it, it updates the first value with both the filled and the second value with both the field and I won't be able to distinguish the field because of the Blade file returns in form of an array.
When I am trying to update with any value it repeats the last value in both the fields, so the output looks like...
shape-square
shape-square
Controller
<?php
public function updateProducts($id, Request $request)
{
$featured = Input::has('featured') ? true : false;
$product = Product::findOrFail($id);
$product->update(array(
'product_name' => $request->input('product_name'),
'product_qty' => $request->input('product_qty'),
'product_sku' => $request->input('product_sku'),
'price' => $request->input('price'),
'reduced_price' => $request->input('reduced_price'),
'cat_id' => $request->input('cat_id'),
'brand_id' => $request->input('brand_id'),
'featured' => $featured,
'description' => $request->input('description'),
'product_spec' => $request->input('product_spec'),
));
$product->update($request->all());
$variants = VariantsOption::where('products_id', $id)->get();
$test = $request->all();
foreach ($variants as $v) {
$x = $v->id;
foreach ($test['variants_id'] as $key => $attrib) {
$var_name = $test['txt'][$key];
$varid = $attrib;
$variants = new VariantsOption;
$data = array(
'variants_id' => $varid,
'variants_name' => $var_name
);
$variants->where('id', '=', $x)->update($data);
}
}
return redirect('/admin/products/');
}
use following in your class
use Illuminate\Database\Eloquent\ModelNotFoundException;
OR add exception handler within your function
// Will return a ModelNotFoundException if no user with that id
try
{
$product = Product::findOrFail($id);
}
// catch(Exception $e) catch any exception
catch(ModelNotFoundException $e)
{
dd(get_class_methods($e)) // lists all available methods for exception object
dd($e)
}
It looks like product with that $id is not found so on update it is adding new product in database.

Handling ajax post data in Zend Framework 2

So i've got some information I send with a Post ajax request like this:
$.ajax("<?php echo $this->url('panel/academy/locals/editlocal')?>", {
method: 'POST',
data: {
id: id, // number
distrito: newDistrito, // string
direccion: newDireccion, // string
telefono1: newTelf1, // string
telefono2: newTelf2, // string
efectivo: $('#local_'+id).find('.efectivo').prop('checked'),
visa: $('#local_'+id).find('.visa').prop('checked'),
mastercard: $('#local_'+id).find('.mastercard').prop('checked'),
american: $('#local_'+id).find('.american').prop('checked'),
deposito: $('#local_'+id).find('.deposito').prop('checked'),
central: newCentral,
}
})
efectivo, visa, american, mastercard and central are all booleans.
In the server I do this:
$prg = $this->prg();
if($prg instanceof \Zend\Http\PhpEnvironment\Response)
return $prg;
elseif ($prg === false)
return new JsonModel(array(
'msg' =>'error prg false',
'success' => false
));
$localForm = new LocalForm();
$localForm->setData($prg);
if(!$localForm->isValid()){
return new JsonModel(array(
'success ' => false,
'error' => 'Invalid',
));
}
$id = (int) $localForm->get('id')->getValue();
$local = (new LocalMapper())->byId($id);
//change local model
$local->setDistrictId($localForm->get('distrito')->getValue());
$local->setAddress($localForm->get('direccion')->getValue());
$local->setPhone1($localForm->get('telefono1')->getValue());
$local->setPhone2($localForm->get('telefono2')->getValue());
$local->setCentral($localForm->get('central')->getValue());
$localpayments = (new LocalPaymentMapper())->byLocalId($id);
// I will have to fix what I'm about to do as soon as possible
foreach($localpayments as $payment){
// Efectivo 1
// Visa 2
// Mastercard 3
// American Express 4
switch($payment->getPaymentId()){
case 1:
if(!$prg['efectivo']){
$payment->delete();
}
break;
case 2:
if(!$prg['visa']){
$payment->delete();
}
break;
case 3:
if(!$prg['mastercard']){
$payment->delete();
}
break;
case 4:
if(!$prg['american']){
$payment->delete();
}
break;
default:
break;
}
}
the problem is that when i try to add an element to the localForm that holds a boolean value like a checkbox the form is always invalid and so I never get to the part where I acccess the db and save the changes the user made. I tried using the $prg array to acces the info but had no luck either. How can I acomplish this? am I trying the wrong approach?
Thanks in advance
here is the full form
<?php
namespace GrouPanel\Form\Locals;
use GrouCore\Form\Form;
use GrouCore\Form\Element\DistrictSelector;
use GrouCore\Form\Element\UserPhone;
use GrouCore\Form\Element\LocalAddress;
use Zend\Form\Element\Checkbox;
class LocalForm extends Form {
public function __construct($name = "localForm") {
parent::__construct ( $name );
$this->setAttribute ( 'novalidate', 'novalidate' );
$localDistrict = new DistrictSelector ( 'distrito' );
$localAddress = new LocalAddress ( 'direccion' );
$localPhone1 = new UserPhone ( 'telefono1' );
$localPhone2 = new UserPhone ( 'telefono2' );
$localCentral = new Checkbox ( 'central' );
$this->add ( array (
'name' => 'id',
'type' => 'text'
) );
$this->add( $localDistrict )
->add( $localAddress )
->add ( $localPhone1 )
->add ( $localPhone2 )
->add ( $localCentral );
$this->getInputFilter ();
}
DistrictSelector, UserPhone and LocalAddress all work as expected, the checkbox seems to be the problem somehow
You use the syntax jQuery.ajax( url [, settings ] ). Try adding key :
dataType: 'json',
in your setting structure.
Http stringified every thing before send.
so you can use 1 or 0 instead of true or false in js.
efectivo: ($('#local_'+id).find('.efectivo').prop('checked')) ? 1 : 0,
add to ajax
dataType: 'json',

Laravel - keeping a running tally of a column through a transformer

So I have a Contribution model. I have a controller that pulls in all the contributions and sends them to a transformer like so:
My Controller:
public function showContributions (Request $request, $memberId)
{
$perPage = $request->input('per_page', 15);
$contribution = parent::getRepo('Contribution');
$contributions = Cache::tags(['contributions'])->remember("contributions.$memberId.2", 60, function() use ($perPage, $memberId, $contribution){
return $contribution->where('vip_id', $memberId)->where('fund_id', 2)->paginate($perPage);
});
$transformedData = $this->fractal->paginatedCollection($contributions, new ContributionTransformer(), 'contributions');
return $this->sendResponse($transformedData['contributions'], $transformedData['meta']);
}
My transformer:
public function transform(Contribution $contribution)
{
setlocale(LC_MONETARY, 'en_US.UTF-8'); // Set so that money_format uses the dollar sign instead of USD. Consider moving to bootstrap
$report = $contribution->report;
$employer = $report->employer;
$employerHours = $contribution->employerHours;
$contributionLocal = $contribution->local->local_code ?? '';
$employerLocal = $employerHours->local->local_code ?? '';
$reciprocalLocal = $contributionLocal === $employerLocal ? '0000' : $employerLocal;
$response = [
'id' => $contribution->member_hours_id,
'report_number' => $contribution->report_number_id,
'employer_code' => $employer->employer_code,
'employer_name' => $employer->employer_name,
'worked_date' => $report->ending_worked_date,
'received_date' => $report->receipt_date,
'report_local' => $contributionLocal,
'reciprocal_local' => $reciprocalLocal,
'unit_type' => $contribution->unitType->code_description,
'units_worked' => $contribution->units_worked,
'credited_units' => $contribution->units_credited,
'rate' => $contribution->unit_multiplier,
'reciprocal_rate' => $employerHours->reciprocal_multiplier,
'calculated_amount' => money_format('%.2n', $contribution->calculated_amount),
'received_amount' => money_format('%.2n', $contribution->actual_amount),
'owed_amount' => money_format('%.2n', $contribution->owed_amount),
];
return $response;
}
One of the fields in the contributions table is sub_hours. What they want me to do is keep a running tally of said field. In each subsequent row return that tally as hours_to_date. So in first row sub_hours is 32 and in the second row it is 60. In the first row hours_to_date will be 32 but in the second row it will be 92 and the third row it will be 92 + sub_hours of row 3 etc. I can't seem to figure out how I should keep track of this running tally and allow the transformer access to it. Any help would be appreciated.
Can you create a property on the transformer class? I haven't used transformers but something like
class ContributionTransformer{
private $tally;
function __construct(){
$this->tally = 0;
}
public function transform(Contribution $contribution){
...
$this->tally += $contribution->sub_hours;
...
}

Unable to save select box options in Laravel 5.1

I am working on my first project using Laravel 5.1. Uses a selectbox in a form.
{!!Form::select('animal_parent[]', array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3', '4' => 'opt4',), null, ['id' => 'animal_parent', 'disabled' => 'disabled', 'multiple' => 'multiple', 'class' => 'form-control'])!!}
Selection limited to two options which need to saved in two columns, male_parent and female_ parent of the animal table.
There are no male_parent and female_ parent element names in the form. Similarly no animal_parent field in animal table.
Values are set as expected in the code given below. However, the insert command does not reflect the newly set values and throws an error.
"ErrorException in helpers.php line 671: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array."
Any help would be much appreciated.
First attempt using mutators
public function setMaleParentAttribute()
{
$parent = Input::get('animal_parent');
$this->attributes['male_parent'] = intval($parent[0]);
}
public function setFemaleParentAttribute(AddAnimalRequest $request)
{
$parent = Input::get('animal_parent);
if (isset($parent[1])) {
$this->attributes['female_parent'] = intval($parent[1]);
} else {
$this->attributes['female_parent'] = intval($parent[0]);
}
unset($request->animal_parent);
}
Second attempt using the store() method in the controller.
$animal = new Animal($request->all());
$parent = Input::get('animal_parent');
$animal['male_parent'] = intval($parent[0]);
if (isset($parent[1])) {
$animal['female_parent'] = intval($parent[1]);
} else {
$animal['female_parent'] = intval($parent[0]);
}
unset($request->animal_parent);
Auth::user()->animals()->save($animal);
return redirect('animals');
The problem was then solved with a change in UI. I feel the problem could have been solved using the below method. Hope that helps someone.
$input = $request->all();
$parent = $input['animal_parent'];
$input['male_parent'] = intval($parent[0]);
if (isset($parent[1])) {
$input['female_parent'] = intval($parent[1]);
} else {
$input['female_parent'] = intval($parent[0]);
}
unset($input['animal_parent']);
$animal = new Animal($input);
$animal->save();`

Custom Widget doesn't display the same amount of choices

I try to create a customWidget with a special tablemethod to only display the pre selected choices of the user, this is the form :
$this->widgetSchema['Books_list'] = new MyWidgetFormThematicSelector(array(
'multiple' => true,
'model' => 'Books',
'table_method' => array('method' => 'getOnlySelected', 'parameters' => array($this->getObject()->getId())),
'expanded' => true,
));
this is the method getOnlySelected:
$q = Doctrine::getTable('BooksAuthors')
->createQuery('ba')
->select('ba.position,ba.name')
->leftJoin('ba.Books b')
->where('ba.BooksAuthors_id = ?', $id);
echo count($q); //return 4
return $q;
this method return 4 elements which is normal then if i try to echo the values of the getChoices method from the widget I get only 1 in return !?
class MyWidgetFormThematicSelector extends sfWidgetFormDoctrineChoiceWithParams {
public function configure($options = array(), $attributes = array())
{
parent::configure($options, $attributes);
}
public function getChoices() {
$choices = parent::getChoices();
echo count($choices); // return 1
return $choices;
}
public function render($name, $value = null, $attributes = array(), $errors = array()) {
return parent::render($name, $value, $attributes, $errors);
}
}
What's going on here ?
I create a similar widget in the same form where the probleme does not occurs, and it s quite the same code...
thx
I solve this problem by setting the attribute 'key_method' => 'myUniqueId', in the form where the widget is called...
Cause Ive got two primary keys in my table and the sfWidgetFormDoctrineChoiceWithParams widget use the one which was identic for all the results as the key for the array choices, so the size of the array was always one...By setting the other primary key as the main key of the getChoices method I get the correct result.

Categories