Skip to content
Advertisement

Best way to build a complex string [closed]

I have the need to put together a somewhat complex URL, here is what I have put together so far:

public static string $comparisonData = 'foo';

public function buildUrl(string $paramTwo, ?string $paramThree, ?string $paramFour, boolean $conditionalOne, string $conditionalTwo)
{
    $url = 'www.base_url.com?paramOne=';

    if ($conditionalOne) {
        $firstParam = $conditionalTwo == self::comparisonData ? 15233 : 1235662;
    } else {
        $firstParam = $conditionalTwo == self::comparisonData ? 123562212 : 2321;
    }

    $params = "&paramTwo=$paramTwo";
    if (!empty($paramThree)) {
        $params .= "&paramThree=$paramThree";
    }
    if (!empty($paramFour)) {
        $params .= "&paramFour=$paramFour";
    }

    return $url . $firstParam . $params;
}

The function works without issue and it won’t be called regularly so doesn’t need to be performant. I am curious to see how others would approach the task.

How would you go about constructing a URL with some optional data, and some conditional data?

Advertisement

Answer

There’s a built-in PHP function called http_build_query that could make your code a bit more readable.

Personally, I’d build up an array first of your required parameters, and then just send buildUrl an array of your parameters, instead of having buildUrl attempt to process it all for you, or you could move that logic to another function.

In your example, you’ve also got string $conditionalOne, which I’m assuming is supposed to be a boolean. This code could be changed again so that processUrl doesn’t take the $conditionalXXX variables, and the condition is processed within the function instead, but I’m not sure what your use-case is so I’m attempting to keep the code familiar to yours.

Here’s an example:

public static string $comparisonData = 'foo';

public function processUrl($conditionalOne, $conditionalTwo, ?array $extraParams): string {
  // Build up Parameter One
  $paramOne = ($conditionalOne
                ? ($conditionalTwo == self::$comparisonData ? 15233 : 1235662)
                : ($conditionalTwo == self::$comparisonData ? 123562212 : 2321)
              );

  // The other parameters are quite simple
  // Using ?? here to fallback to an empty array for merge, if $extraParams is NULL
  $params = ['paramOne' => $paramOne] + ($extraParams ?? []);
  return $this->buildUrl($params);
}

private function buildUrl(array $params): string {
  $baseUrl = 'https://www.example.com/?';
  return $baseUrl . http_build_query($params);
}

Usage:

$className->processUrl(TRUE, FALSE, [
  'paramTwo' => 'foo',
  'paramThree' => 'bar',
  'paramFour' => NULL, // http_build_query strips NULL key/values
]);

// Output:
https://www.example.com/?paramOne=1235662¶mTwo=foo¶mThree=bar
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement