The price service
starts with the catalogue.
Then each branch
has a few overrides.
Merge them,
branch wins,
done.
$prices = array_merge($catalogue, $branchPrices);
$price = $prices[$productId];
For years
the keys were SKUs.
"BOLT-M10-50".
"PLY-18-2440".
It worked perfectly.
Then the products
moved to numeric IDs,
and the same line
started quoting
the wrong prices.
Not missing prices.
Wrong ones.
A box of screws
at the price of a door.
Here is the mechanism.
array_merge
treats string keys
and integer keys
differently.
String keys
are matched.
A later value
overwrites an earlier one.
That is the merge
you thought you wrote.
Integer keys
are not matched at all.
They are renumbered,
from zero,
in order.
The overrides
do not replace anything.
They are appended
to the end.
So $prices[1042]
is no longer product 1042.
It is whatever
ended up
in position 1042.
And with five thousand products,
there is always something there.
No warning.
No null.
Just a price
that belongs to someone else.
PHP also turns
a key like "1042"
into the integer 1042,
so even IDs
stored as strings
get renumbered.
The tests passed
because the fixtures
still used SKUs.
And the code review
saw one familiar line
that had not changed.
Nobody reviews a line
that is not in the diff.
Here is what to use instead.
If the right side should win:
$prices = array_replace($catalogue, $branchPrices);
array_replace keeps every key
and overwrites by key.
The + operator
keeps keys too,
but the left side wins
where both have one.
So write it the other way round:
$prices = $branchPrices + $catalogue;
Then add a test
with real numeric IDs,
where an override
changes a product
that is not first in the list.
And check the price you got
belongs to the product you asked for.
array_merge
merges by name
and stacks by number.
Your keys changed type,
and the function
changed its mind.
– Serguey Asael Shinder
