LoginSignup
1
1

More than 5 years have passed since last update.

雑だけど、cakephpのpassedArgsをmergeしてurlを返すメソッド書いた

Posted at

もともとhelper用に書いてました。
非常にやりかたが雑です。

/**
 * passedArgsをマージしてURLを返す
 * @param string $url 相対URLまたは絶対URL
 * @param array $merge_array 上書きするパラメータ(key=>value)
 * @return string
 */
public function merge_passed_args_url($url, $merge_array) {
    if(strpos($url, 'http://') !== FALSE) {
        $protocol = 'http://';
        $url = str_replace($protocol, '', $url);
    }
    if(strpos($url, 'https://') !== FALSE) {
        $protocol = 'https://';
        $url = str_replace($protocol, '', $url);
    }

    $segments = explode('/', $url);
    $passed_keys = array();
    foreach($segments as $key => $segment) {
        if(strpos($segment, ':') !== FALSE) {
            list($passed_key, $passed_value) = explode(':', $segment);
            $passed_keys[] = $passed_key;

            if(array_key_exists($passed_key, $merge_array)) {
                // 存在する場合は書き換える
                $segments[$key] = $passed_key.':'. $merge_array[$passed_key];
            }
        }
    }

    $url = rtrim(implode('/', $segments), '/'). '/';
    $no_added_keys = array_diff(array_keys($merge_array), $passed_keys);
    foreach($no_added_keys as $key) {
        $url .= $key. ':'. $merge_array[$key]. '/';
    }

    if(!empty($protocol)) {
        $url = $protocol . $url;
    }
    return $url;
}

merge_passed_args_url(Router::url(), array('key'=>'value'));

もっとめんどくさくない方法が欲しい。
使う人居ないと思うけど使う人はできればコメントしてくださいな

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1