Laravel service and UUID location - php

I have a method in the controller that calls a service, specifically this method that returns quotes for activities. I'm unsure about the correctness of the logic. Is it correct to pass the parameters as UUIDs to the service and then convert them internally to obtain the internal ID? Internally, I work with IDs, while publicly, I expose UUIDs.
Thank you!
public function getQuotes(string $businessUUID, string $businessTypeUUID, array $filters): Collection
{
// Get the internal id from the uuid
$filters['business_id'] = $this->businessService->getBusinessByUUID($businessUUID)->id;
$filters['business_type_id'] = $this->businessTypeService->getBusinessTypeByUUID($businessTypeUUID)->id;
// Retrieve the quotes that match the given filters
$quotes = BusinessQuote::query()->withFilters($filters)->get();
// If no quotes match the given filters
if ($quotes->isEmpty()) {
throw new ModelNotFoundException(__('Quotes not found'));
}
// Return the quotes
return $quotes;
}

Yes, this approach is correct and safe because a chance to guess UUID is currently impossible. Using integer IDs you get better performance than working with UUID internally.
Keep in mind, is recommended to use UUID v4 for maximum security.

Related

Convert single property for response with the FOSRestBundle in Symfony 5

I'm working with numbers with a lot of decimal places in my symfony application. In my doctrine entity I have for example this property:
/**
* #ORM\Column(type="float")
*/
private float $value;
In my mysql database I have this value for example: 0.00000000020828579949508
When I dump that in PHP I'm getting this: float(9.3722658865184E-7). I also made an API with the FOSRestBundle. In that API I want to return the value not in exponential form with at least 12 of it's decimal places. I think in that case I have to provide the value as string, correct? I figured out that I can convert it to string with something like this: sprintf("%.12f", $myEntity->getValue()). But I have two questions now:
How can I convert a single property for response with the FOSRestBundle? So that I return the "value" property as string, even if it is a float normally.
Is there a general best practice or any tips to work with such numbers in symfony, doctrine and the FOSRestBundle?
Right now this is my controller action:
public function getData(): Response
{
$repository = $this->getDoctrine()->getRepository(MyEntity::class);
$data = $repository->findAll();
return $this->handleView($this->view($data));
}
Assuming you are using Symfony version 3.x, you can use the JMS #Expose and #Accessor annotations to control how your entity property is serialized into response data. More info here. However, consider that JMS is bypassed if all you want is to pass your entity to the Twig template rendering engine.
The Doctrine float column type is the correct type to use when handling larger sized floating point numbers such as yours. Your issue is more related to the scientific notation that PHP is designed to use in order to represent these large floats. Allowing arithmetic such as 2.1E-10 + 2.2E-9, but also requiring extra steps to convert their notation to a perhaps more human friendly readable form by using functions such as sprintf and number_format.

How to query parameters in URL - json api

I have to call api url to access the json object from it. in its tutorial, they provide some variables we can access through url, these variables have names different of the attributes name of the json object.
ex: url&parm1=val1
json object
{
"parm1_name": "val1"
}
My question:
How to return specific values depend on the attributes of the json object?
Do we have to use the parameter names which are provided on their website?
what the difference between "?pram1=val" and "pram1=:val"
How to query as we do in databases using greater or less than?
I use PHP and crul to retrieve the json object.
The value that each parameter/s return should be documented by the api and is up to the provider.
Yes, you have to use the parameters the api/website requires to return the value. If the api/website expects a value to return something then you have to provide the expected value. That also means the website will only recognize values that they look for.
The paramaters are key and value so
?param=val1 => key "param" equals "val1"
?param=:val1 => key "param" equals ":val1"
Unless the api provides a way to do then you can't. The limitations of what you can do is set by the api.
Api is essentially this:
<?php
// it gets ?id=val
// so if the GET parameters were ?id=1&name=blue&do=add
// it would only recognize id parameters the other parameters wouldnt change a thing
$val = $_GET["id"];
if $val == 1 {
return $data;
}
?>
API must provide a way for you to e.g. search for "greater & less than" otherwise you cannot do it.

How to force int to string in Laravel JSON?

I've recently updated my server to a newer version of MySQL and PHP 7 for various reasons. On my previous instance, running PHP 5.5, Laravel's response()->json() always converted tinyint's into a string. Now running newer server software, it's returning me int's -as it should...
I'd have to change a lots of my codebase to either cast types / convert them into a string manually, whic I'm trying to avoid at the moment.
Is there a way to somehow force response()->json() to return int's as string's?
Is there a way to somehow force response()->json() to return int's as string's
I don't want to change the code base - do not want to cast types, convert it,
No. There's no option for that. You need to do that yourself if needed.
There is a way to cast integer into string in laravel
in your model you can cast id to string. Its as follows
protected $casts = [ 'id' => 'string' ];
But the downside is that you would have to do that for all Models.
If you don't want to modify a lot of code you could run response data through a quick and dirty function. Instead of going directory to JSON you should instead grab the data as a nested array. Then put it through a function like this:
function convertIntToString ($myArray) {
foreach ($myArray as $thisKey => $thisValue) {
if (is_array($thisValue)) {
// recurse to handle a nested array
$myArray[$thisKey] = convertIntToString($thisValue);
} elseif (is_integer($thisValue)) {
// convert any integers to a string
$myArray[$thisKey] = (string) $thisValue;
}
}
return $myArray;
}
The function will convert integers to strings and use recursion to handle nested arrays. Take the output from that and then convert it to JSON.
The best solution for me is to to use attribute casting and
Fractal transformers
Fractal transformers are extremely useful when you have complex responses with multiple relations included.
You can typecast it to string:
return response->json(["data" => (string)1]);

Unify variable types of array elements

After hours of debugging, I found an error in one of my scripts. For saving different event types in a database, I have an array of unique data for each event that can be used to identify the event.
So I basically have some code like
$key = md5(json_encode($data));
to generate a unique key for each event.
Now, in some cases, a value in the $data array is an integer, sometimes a string (depending on where it comes from - database or URL). That causes the outputs of json_encode() to be different from each other, though - once including quotes, once not.
Does anybody know a way to "unify" the variable types in the $data array? That would probably mean converting all strings that only contain an integer value to integer. Anything else I have to take care of when using json_encode()?
array_walk_recursive combined with a function you have written to the effect of maybe_intval which performs the conversion you talk about on a single element.
EDIT: having read the documentation for array_walk_recursive more closely you'll actually want to write your own recursive function
function to_json($obj){
if(is_object($obj))
$obj=(array)$obj;
if(is_array($obj))
return array_map('to_json',$obj);
return "$obj"; // or return is_int($obj)?intval($obj):$obj;
}

Best method of passing/return values

The reason I am asking this question is because I have landed my first real (yes, a paid office job - no more volunteering!) Web Development job about two months ago. I have a couple of associates in computer information systems (web development and programming). But as many of you know, what you learn in college and what you need in the job site can be very different and much more. I am definitely learning from my job - I recreated the entire framework we use from scratch in a MVC architecture - first time doing anything related to design patterns.
I was wondering what you would recommend as the best way to pass/return values around in OO PHP? Right now I have not implement any sort of standard, but I would like to create one before the size of the framework increases any more. I return arrays when more than 1 value needs to get return, and sometimes pass arrays or have multiple parameters. Is arrays the best way or is there a more efficient method, such as json? I like the idea of arrays in that to pass more values or less, you just need to change the array and not the function definition itself.
Thank you all, just trying to become a better developer.
EDIT: I'm sorry all, I thought I had accepted an answer for this question. My bad, very, very bad.
How often do you run across a situation where you actually need multiple return values? I can't imagine it's that often.
And I don't mean a scenario where you are returning something that's expected to be an enumerable data collection of some sort (i.e., a query result), but where the returned array has no other meaning that to just hold two-or-more values.
One technique the PHP library itself uses is reference parameter, such as with preg_match(). The function itself returns a single value, a boolean, but optionally uses the supplied 3rd parameter to store the matched data. This is, in essence, a "second return value".
Definitely don't use a data interchange format like JSON. the purpose of these formats is to move data between disparate systems in an expected, parse-able way. In a single PHP execution you don't need that.
You can return anything you want: a single value, an array or a reference (depending on the function needs). Just be consistent.
But please don't use JSON internally. It just produces unnecessary overhead.
I also use arrays for returning multiple values, but in practice it doesn't happen very often. If it does, it's generally a sensible grouping of data, such as returning array('x'=>10,'y'=>10) from a function called getCoordinates(). If you find yourself doing lots of processing and returning wads of data in arrays from a lot of functions, there's probably some refactoring that can be done to put the work into smaller units.
That being said, you mentioned:
I like the idea of arrays in that to pass more values or less, you just need to change the array and not the function definition itself.
In that regard, another technique you might be interested in is using functions with variable numbers of arguments. It is perfectly acceptable to declare a function with no parameters:
function stuff() {
//do some stuff
}
but call it with all the parameters you care to give it:
$x = stuff($var1, $var2, $var3, $var4);
By using func_get_args(), func_get_arg() (singular) and func_num_args() you can easily find/loop all the parameters that were passed. This works very well if you don't have specific parameters in mind, say for instance a sum() function:
function sum()
{
$out = 0;
for($i = 0; $i < $c = func_num_args(); $i++) {
$out += func_get_arg($i);
}
return $out;
}
//echoes 35
echo sum(10,10,15);
Food for thought, maybe you'll find it useful.
The only thing I'm careful to avoid passing/returning arrays where the keys have "special" meaning. Example:
<?php
// Bad. Don't pass around arrays with 'special' keys
$personArray = array("eyeColor"=>"blue", "height"=>198, "weight"=>103, ...);
?>
Code that uses an array like this is harder to refactor and debug. This type of structure is better represented as an object.
<?php
Interface Person {
/**
* #return string Color Name
*/
public function getEyeColor();
...
}
?>
This interface provides a contract that the consuming code can rely on.
Other than that I can't think of any reason to limit yourself.
Note: to be clear, associative arrays are great for list data. like:
<?php
// Good array
$usStates = array("AL"=>"ALABAMA", "AK"="ALASKA", ... );
?>

Categories