I am developing an API that has one call that accepts a big JSON object.
Based on this object, there are 10 possible parsing scenarios, i.e. if field xxxx.xxx is present, go with scenario 5.
We currently have around 10 if statements in a controller function of over 200 lines, which decides which scenario to choose. The cyclomatic complexity is over 5000 and the nPath complexity is over 10 million
As this is not scalable, I finally made time to refactor this and make it more loosely coupled
What would be the best possible design pattern for this case?
I was thinking of having multiple parser classes that I loop through and each of them has a function called canHandle($jsonObject), and if certain fields are present, canHandle will return true and that class can then do it's logic.
Is this similar to the strategy pattern?
More background:
It is a booking tool for point to point travel.
So say I want to travel from an airport to a trainstation, the JSON would have the following fields:
route.pickuppoint.airport.iata
route.dropoffpoint.trainstation.id
There are multiple entities that can exist under pickuppoint
and dropoffpoint
(trainstations/airports/addresses/flight numbers) and they have to be parsed differently into our database
So if anyone calls the API with an airport in the pickup, I need to parse the airport and translate it to an address using some external api's and put it in the DB, the same goes for the other entities
Code example:
if (isset($data['Address']['Street'])) {
// Parse address
} elseif (isset($data['Location']['Latitude'])) {
// Parse Location
} elseif (isset($data['Airport']['Id'])) {
// Parse airport
} elseif (isset($data['Flight']['FlightNumber'])) {
// Resolve flight number and parse
} elseif (isset($data['Trainstation']['id'])) {
// Resolve train station
}
As you can imagine, if we were to add more options, this code would only get uglier