feat: add SiteURI class - #7252

Merged
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL
Jul 11, 2023
Merged

feat: add SiteURI class#7252
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL

Conversation

@kenjis

@kenjiskenjis commented Feb 14, 2023

Copy link
Copy Markdown
Member

Description
This PR is needed for #7123

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

  • add SiteURI class
    • The $routePath never starts with /.
    • If the path ends with /, the URI retains the trailing /.
    • getPath() returns the full URI path.
    • getRoutePath() returns the path relative to baseURL.

Related #5930, #7239, #7249, #7251

Checklist:

  • Securely signed commits
  • Component(s) with PHPDoc blocks, only if necessary or adds value
  • Unit testing, with >80% coverage
  • User guide updated
  • Conforms to style guide

@kenjiskenjis added enhancement PRs that improve existing functionalities 4.4 labels Feb 14, 2023
@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from 2d602ea to 87c90caCompareFebruary 14, 2023 08:48
Comment threadsystem/HTTP/SiteURI.php Outdated
@michalsn

Copy link
Copy Markdown
Member

Maybe this is a silly question, but... as I understand, this new class will bring full PSR-7 compatibility, right?

I don't see any related changes in the framework so we won't rely on it. The question is, who needs this class and for what?

Like... I saw your description:

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

But I'm afraid I don't fully understand the use cases.

@kenjis

kenjis commented Feb 15, 2023

Copy link
Copy Markdown
MemberAuthor

This PR only adds a new SiteURI class, and does not change the current framework behavior yet.

In the next PR(s), I will do:

  • add a factory to create the SiteURI instance for the current URL: feat: add SiteURIFactory #7256
  • set the SiteURI instance in the uri property of the Request
  • use the SiteURI instance when getting the current URL like current_url()

About compatibility with PSR-7, the URI class will be cleaner because site-related functions like baseURL, will be separated into the SiteURI class. And the URI class will be easier to change.

Finally, I think URI and SiteURL can be made fully compatible (and having some extended functions) with PSR-7.

@kenjiskenjis mentioned this pull request Feb 15, 2023
5 tasks

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am obviously in favor of this but I want to be sure we get reviews from @lonnieezell and @iRedds and anyone else who was opposed to the idea originally.

@lonnieezell

lonnieezell commented Feb 15, 2023

Copy link
Copy Markdown
Member

I was purposefully not commenting since my position was already known and it seemed I was overruled :)

I'm confused why we need a second class that does 99% of the same things as the URI class. The URI class is just for working with URIs in general, crafted to meet the RFC as best we could at the time. It seems like all other issues should be fixed where it's used, or the base class should be changed to support our needs.

The implementation itself is solid enough. Though if we're going to include it, we need docs and guidance on when to use which one.

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers. What is the point of this other then to throw confusion about which class people should use when? I figured it was to fix issues in how the framework was returning answers, but it doesn't seem like we're actually doing that.

@michalsn

Copy link
Copy Markdown
Member

I agree with @lonnieezell. I don't understand why we need a second class to handle URLs. Can somebody give me a clear example of where it will be useful?

AFAIK the only issue that we have now with the URI class is that it does not follow PSR-7 (it's something path related).

Also, if the goal for both classes is to follow the PSR-7, what will be the difference? Wouldn't it be better to see some additional methods added to the current class instead?

@kenjis

kenjis commented Feb 16, 2023

Copy link
Copy Markdown
MemberAuthor

I don't understand why we need a second class to handle URLs.

Because we have already two kinds of concept URI,
and if we have two classes, It is easier to understand for us.

  1. URI: a URI
  2. SiteURI: a URI for a CI4 app site.

SiteURI has its own properties like baseURL, indexPage and we cannot change the URI path
inside baseURL (subfolders). Only the URI path after indexPage does matter.

Now we are already confusing 1. and 2. So we have two kinds of URI segments for one SiteURL.
See #7123 (comment)

@kenjis

Copy link
Copy Markdown
MemberAuthor

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers.

This fix (and refactoring) will be long story. This PR is just the first one.
We will use the new class in all places after all. Please wait for incoming PRs.

@MGatner

Copy link
Copy Markdown
Member

I won't repeat my arguments, the original PR is here with discussion: #4647

I would like to point out that after doing a deep dive on URI handling and bug fixes both @kenjis and I came to the same conclusion, independently. I think the problem is larger than credited and may indeed merit the potential confusion/clutter of an additional class.

@lonnieezell

Copy link
Copy Markdown
Member

After giving this a bit more thought, I think I'm ok with this on 2 conditions:

  1. It's designed for internal use within the request class and URL helper functions. Not intended for public use or really even documented. This avoids the confusion to end users, while still providing a "URI in Request is the source of truth" that @MGatner was looking for in the previous PR.
  2. It's saved for 5.0 (which we should be working on now....) since it's too big of a potential BC break.

@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from f65a55c to 72f76a6CompareFebruary 17, 2023 01:04
@iRedds

iRedds commented Feb 17, 2023

Copy link
Copy Markdown
Collaborator
$uri = $this->request->getUri();
echo (string) $uri; // "http://localhost:8888/ci431/public/test?a=b" → Okayecho$uri->getPath(); // "test" → NG. It should be "/ci431/public/test" when following PSR-7

And I think that such behavior corresponds to PSR.

// for http://localhost:8888/ci431/public/test?a=bURI::getPath(); // => /ci431/public/test// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)// Accordingly, the leading slash will determine whether the path is absolute or rootless// for http://localhost:8888/{base_path}/test?a=bURI::withPath('/xxx'); // http://localhost:8888/xxx?a=b// for http://localhost:8888/{base_path}/test?a=bURI::withPath('xxx'); // http://localhost:8888/{base_path}/xxx?a=b

php-fig/fig-standards#503

@kenjis

Copy link
Copy Markdown
MemberAuthor

What is {base_path} in this case? How do you define it?

// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)

@iRedds

Copy link
Copy Markdown
Collaborator

@kenjis app.baseURL = 'http://localhost:8888{/ci431/public/}' <- base path

@kenjis

Copy link
Copy Markdown
MemberAuthor

I don't get it.
How do you set it in PSR-7 URI object?

@iRedds

Copy link
Copy Markdown
Collaborator

There are no objects in PSR-7. Interfaces only. That is, mandatory public methods for PSR compliance.
A class implementing UriInterface should not be limited to UriInterface methods and may contain a method that sets base_path or base_url or whatever is needed for it to work properly.

@kenjis

Copy link
Copy Markdown
MemberAuthor

Many frameworks provide the ability to get the "base path," usually considered the path up to and including the front controller. As an example, if the application is served at http://example.com/b2b/index.php, and the current URI used to request it is http://example.com/b2b/index.php/customer/register, the functionality to retrieve the base path would return /b2b/index.php. This value can then be used by routers to strip that path segment prior to attempting a match.
https://www.php-fig.org/psr/psr-7/meta/#why-is-no-functionality-included-for-retrieving-the-base-path

 * If an HTTP path is intended to be host-relative rather than path-relative
* then it must begin with a slash ("/"). HTTP paths not starting with a slash
* are assumed to be relative to some base path known to the application or
* consumer.
...
*/
public function withPath($path);

https://www.php-fig.org/psr/psr-7/

This means like this?

  • if we call URI::withPath('foo/bar'), the path foo/bar is relative to some base path known to the application.
  • the new URI instance getPath() will return foo/bar?

@kenjis

Copy link
Copy Markdown
MemberAuthor
<?phprequire__DIR__ . '/vendor/autoload.php';
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
echo$uri . PHP_EOL; // http://localhost/ci4/foo/barecho$uri->getPath() . PHP_EOL; // /ci4/foo/bar

https://uri.thephpleague.com/uri/6.0/psr7/

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');

PHP Fatal error: Uncaught League\Uri\Exceptions\SyntaxError: If an authority is present the path must be empty or start with a /. in /.../league-uri/vendor/league/uri/src/Uri.php:921

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useSlim\Psr7\Factory\UriFactory;
$factory = newUriFactory();
$uri = $factory->createUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@kenjis

Copy link
Copy Markdown
MemberAuthor
useNyholm\Psr7\Uri;
$uri = newUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@iRedds

Copy link
Copy Markdown
Collaborator
  • the new URI instance getPath() will return foo/bar?

empty string

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great! I feel validated in the need for this given how much code is in SiteURI on top of URI. I appreciate your verbosity in naming variables and methods - it is easy to overlook pieces which has led to many bugs in the past. I think this will be a good step forward.

I assume the URL Helper methods get changed in the next PR? I haven't looked at that one yet...

Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php
Comment threadsystem/HTTP/URI.php Outdated
Comment threadsystem/HTTP/URI.php Outdated
@kenjis
kenjis merged commit 09f62eb into codeigniter4:4.4Jul 11, 2023
@kenjis
kenjis deleted the feat-SiteURL branch July 11, 2023 23:14
@kenjis

Copy link
Copy Markdown
MemberAuthor

@TimexPeachtree@MGatner Thank you for approvals.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancementPRs that improve existing functionalities

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants

@kenjis@michalsn@lonnieezell@MGatner@iRedds@samsonasik@TimexPeachtree
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

feat: add SiteURI class - #7252

Merged
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL
Jul 11, 2023
Merged

feat: add SiteURI class#7252
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL

Conversation

@kenjis

@kenjiskenjis commented Feb 14, 2023

Copy link
Copy Markdown
Member

Description
This PR is needed for #7123

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

  • add SiteURI class
    • The $routePath never starts with /.
    • If the path ends with /, the URI retains the trailing /.
    • getPath() returns the full URI path.
    • getRoutePath() returns the path relative to baseURL.

Related #5930, #7239, #7249, #7251

Checklist:

  • Securely signed commits
  • Component(s) with PHPDoc blocks, only if necessary or adds value
  • Unit testing, with >80% coverage
  • User guide updated
  • Conforms to style guide

@kenjiskenjis added enhancement PRs that improve existing functionalities 4.4 labels Feb 14, 2023
@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from 2d602ea to 87c90caCompareFebruary 14, 2023 08:48
Comment threadsystem/HTTP/SiteURI.php Outdated
@michalsn

Copy link
Copy Markdown
Member

Maybe this is a silly question, but... as I understand, this new class will bring full PSR-7 compatibility, right?

I don't see any related changes in the framework so we won't rely on it. The question is, who needs this class and for what?

Like... I saw your description:

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

But I'm afraid I don't fully understand the use cases.

@kenjis

kenjis commented Feb 15, 2023

Copy link
Copy Markdown
MemberAuthor

This PR only adds a new SiteURI class, and does not change the current framework behavior yet.

In the next PR(s), I will do:

  • add a factory to create the SiteURI instance for the current URL: feat: add SiteURIFactory #7256
  • set the SiteURI instance in the uri property of the Request
  • use the SiteURI instance when getting the current URL like current_url()

About compatibility with PSR-7, the URI class will be cleaner because site-related functions like baseURL, will be separated into the SiteURI class. And the URI class will be easier to change.

Finally, I think URI and SiteURL can be made fully compatible (and having some extended functions) with PSR-7.

@kenjiskenjis mentioned this pull request Feb 15, 2023
5 tasks

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am obviously in favor of this but I want to be sure we get reviews from @lonnieezell and @iRedds and anyone else who was opposed to the idea originally.

@lonnieezell

lonnieezell commented Feb 15, 2023

Copy link
Copy Markdown
Member

I was purposefully not commenting since my position was already known and it seemed I was overruled :)

I'm confused why we need a second class that does 99% of the same things as the URI class. The URI class is just for working with URIs in general, crafted to meet the RFC as best we could at the time. It seems like all other issues should be fixed where it's used, or the base class should be changed to support our needs.

The implementation itself is solid enough. Though if we're going to include it, we need docs and guidance on when to use which one.

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers. What is the point of this other then to throw confusion about which class people should use when? I figured it was to fix issues in how the framework was returning answers, but it doesn't seem like we're actually doing that.

@michalsn

Copy link
Copy Markdown
Member

I agree with @lonnieezell. I don't understand why we need a second class to handle URLs. Can somebody give me a clear example of where it will be useful?

AFAIK the only issue that we have now with the URI class is that it does not follow PSR-7 (it's something path related).

Also, if the goal for both classes is to follow the PSR-7, what will be the difference? Wouldn't it be better to see some additional methods added to the current class instead?

@kenjis

kenjis commented Feb 16, 2023

Copy link
Copy Markdown
MemberAuthor

I don't understand why we need a second class to handle URLs.

Because we have already two kinds of concept URI,
and if we have two classes, It is easier to understand for us.

  1. URI: a URI
  2. SiteURI: a URI for a CI4 app site.

SiteURI has its own properties like baseURL, indexPage and we cannot change the URI path
inside baseURL (subfolders). Only the URI path after indexPage does matter.

Now we are already confusing 1. and 2. So we have two kinds of URI segments for one SiteURL.
See #7123 (comment)

@kenjis

Copy link
Copy Markdown
MemberAuthor

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers.

This fix (and refactoring) will be long story. This PR is just the first one.
We will use the new class in all places after all. Please wait for incoming PRs.

@MGatner

Copy link
Copy Markdown
Member

I won't repeat my arguments, the original PR is here with discussion: #4647

I would like to point out that after doing a deep dive on URI handling and bug fixes both @kenjis and I came to the same conclusion, independently. I think the problem is larger than credited and may indeed merit the potential confusion/clutter of an additional class.

@lonnieezell

Copy link
Copy Markdown
Member

After giving this a bit more thought, I think I'm ok with this on 2 conditions:

  1. It's designed for internal use within the request class and URL helper functions. Not intended for public use or really even documented. This avoids the confusion to end users, while still providing a "URI in Request is the source of truth" that @MGatner was looking for in the previous PR.
  2. It's saved for 5.0 (which we should be working on now....) since it's too big of a potential BC break.

@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from f65a55c to 72f76a6CompareFebruary 17, 2023 01:04
@iRedds

iRedds commented Feb 17, 2023

Copy link
Copy Markdown
Collaborator
$uri = $this->request->getUri();
echo (string) $uri; // "http://localhost:8888/ci431/public/test?a=b" → Okayecho$uri->getPath(); // "test" → NG. It should be "/ci431/public/test" when following PSR-7

And I think that such behavior corresponds to PSR.

// for http://localhost:8888/ci431/public/test?a=bURI::getPath(); // => /ci431/public/test// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)// Accordingly, the leading slash will determine whether the path is absolute or rootless// for http://localhost:8888/{base_path}/test?a=bURI::withPath('/xxx'); // http://localhost:8888/xxx?a=b// for http://localhost:8888/{base_path}/test?a=bURI::withPath('xxx'); // http://localhost:8888/{base_path}/xxx?a=b

php-fig/fig-standards#503

@kenjis

Copy link
Copy Markdown
MemberAuthor

What is {base_path} in this case? How do you define it?

// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)

@iRedds

Copy link
Copy Markdown
Collaborator

@kenjis app.baseURL = 'http://localhost:8888{/ci431/public/}' <- base path

@kenjis

Copy link
Copy Markdown
MemberAuthor

I don't get it.
How do you set it in PSR-7 URI object?

@iRedds

Copy link
Copy Markdown
Collaborator

There are no objects in PSR-7. Interfaces only. That is, mandatory public methods for PSR compliance.
A class implementing UriInterface should not be limited to UriInterface methods and may contain a method that sets base_path or base_url or whatever is needed for it to work properly.

@kenjis

Copy link
Copy Markdown
MemberAuthor

Many frameworks provide the ability to get the "base path," usually considered the path up to and including the front controller. As an example, if the application is served at http://example.com/b2b/index.php, and the current URI used to request it is http://example.com/b2b/index.php/customer/register, the functionality to retrieve the base path would return /b2b/index.php. This value can then be used by routers to strip that path segment prior to attempting a match.
https://www.php-fig.org/psr/psr-7/meta/#why-is-no-functionality-included-for-retrieving-the-base-path

 * If an HTTP path is intended to be host-relative rather than path-relative
* then it must begin with a slash ("/"). HTTP paths not starting with a slash
* are assumed to be relative to some base path known to the application or
* consumer.
...
*/
public function withPath($path);

https://www.php-fig.org/psr/psr-7/

This means like this?

  • if we call URI::withPath('foo/bar'), the path foo/bar is relative to some base path known to the application.
  • the new URI instance getPath() will return foo/bar?

@kenjis

Copy link
Copy Markdown
MemberAuthor
<?phprequire__DIR__ . '/vendor/autoload.php';
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
echo$uri . PHP_EOL; // http://localhost/ci4/foo/barecho$uri->getPath() . PHP_EOL; // /ci4/foo/bar

https://uri.thephpleague.com/uri/6.0/psr7/

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');

PHP Fatal error: Uncaught League\Uri\Exceptions\SyntaxError: If an authority is present the path must be empty or start with a /. in /.../league-uri/vendor/league/uri/src/Uri.php:921

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useSlim\Psr7\Factory\UriFactory;
$factory = newUriFactory();
$uri = $factory->createUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@kenjis

Copy link
Copy Markdown
MemberAuthor
useNyholm\Psr7\Uri;
$uri = newUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@iRedds

Copy link
Copy Markdown
Collaborator
  • the new URI instance getPath() will return foo/bar?

empty string

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great! I feel validated in the need for this given how much code is in SiteURI on top of URI. I appreciate your verbosity in naming variables and methods - it is easy to overlook pieces which has led to many bugs in the past. I think this will be a good step forward.

I assume the URL Helper methods get changed in the next PR? I haven't looked at that one yet...

Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php
Comment threadsystem/HTTP/URI.php Outdated
Comment threadsystem/HTTP/URI.php Outdated
@kenjis
kenjis merged commit 09f62eb into codeigniter4:4.4Jul 11, 2023
@kenjis
kenjis deleted the feat-SiteURL branch July 11, 2023 23:14
@kenjis

Copy link
Copy Markdown
MemberAuthor

@TimexPeachtree@MGatner Thank you for approvals.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancementPRs that improve existing functionalities

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants

@kenjis@michalsn@lonnieezell@MGatner@iRedds@samsonasik@TimexPeachtree
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat: add SiteURI class - #7252

Merged
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL
Jul 11, 2023
Merged

feat: add SiteURI class#7252
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL

Conversation

@kenjis

@kenjiskenjis commented Feb 14, 2023

Copy link
Copy Markdown
Member

Description
This PR is needed for #7123

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

  • add SiteURI class
    • The $routePath never starts with /.
    • If the path ends with /, the URI retains the trailing /.
    • getPath() returns the full URI path.
    • getRoutePath() returns the path relative to baseURL.

Related #5930, #7239, #7249, #7251

Checklist:

  • Securely signed commits
  • Component(s) with PHPDoc blocks, only if necessary or adds value
  • Unit testing, with >80% coverage
  • User guide updated
  • Conforms to style guide

@kenjiskenjis added enhancement PRs that improve existing functionalities 4.4 labels Feb 14, 2023
@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from 2d602ea to 87c90caCompareFebruary 14, 2023 08:48
Comment threadsystem/HTTP/SiteURI.php Outdated
@michalsn

Copy link
Copy Markdown
Member

Maybe this is a silly question, but... as I understand, this new class will bring full PSR-7 compatibility, right?

I don't see any related changes in the framework so we won't rely on it. The question is, who needs this class and for what?

Like... I saw your description:

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

But I'm afraid I don't fully understand the use cases.

@kenjis

kenjis commented Feb 15, 2023

Copy link
Copy Markdown
MemberAuthor

This PR only adds a new SiteURI class, and does not change the current framework behavior yet.

In the next PR(s), I will do:

  • add a factory to create the SiteURI instance for the current URL: feat: add SiteURIFactory #7256
  • set the SiteURI instance in the uri property of the Request
  • use the SiteURI instance when getting the current URL like current_url()

About compatibility with PSR-7, the URI class will be cleaner because site-related functions like baseURL, will be separated into the SiteURI class. And the URI class will be easier to change.

Finally, I think URI and SiteURL can be made fully compatible (and having some extended functions) with PSR-7.

@kenjiskenjis mentioned this pull request Feb 15, 2023
5 tasks

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am obviously in favor of this but I want to be sure we get reviews from @lonnieezell and @iRedds and anyone else who was opposed to the idea originally.

@lonnieezell

lonnieezell commented Feb 15, 2023

Copy link
Copy Markdown
Member

I was purposefully not commenting since my position was already known and it seemed I was overruled :)

I'm confused why we need a second class that does 99% of the same things as the URI class. The URI class is just for working with URIs in general, crafted to meet the RFC as best we could at the time. It seems like all other issues should be fixed where it's used, or the base class should be changed to support our needs.

The implementation itself is solid enough. Though if we're going to include it, we need docs and guidance on when to use which one.

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers. What is the point of this other then to throw confusion about which class people should use when? I figured it was to fix issues in how the framework was returning answers, but it doesn't seem like we're actually doing that.

@michalsn

Copy link
Copy Markdown
Member

I agree with @lonnieezell. I don't understand why we need a second class to handle URLs. Can somebody give me a clear example of where it will be useful?

AFAIK the only issue that we have now with the URI class is that it does not follow PSR-7 (it's something path related).

Also, if the goal for both classes is to follow the PSR-7, what will be the difference? Wouldn't it be better to see some additional methods added to the current class instead?

@kenjis

kenjis commented Feb 16, 2023

Copy link
Copy Markdown
MemberAuthor

I don't understand why we need a second class to handle URLs.

Because we have already two kinds of concept URI,
and if we have two classes, It is easier to understand for us.

  1. URI: a URI
  2. SiteURI: a URI for a CI4 app site.

SiteURI has its own properties like baseURL, indexPage and we cannot change the URI path
inside baseURL (subfolders). Only the URI path after indexPage does matter.

Now we are already confusing 1. and 2. So we have two kinds of URI segments for one SiteURL.
See #7123 (comment)

@kenjis

Copy link
Copy Markdown
MemberAuthor

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers.

This fix (and refactoring) will be long story. This PR is just the first one.
We will use the new class in all places after all. Please wait for incoming PRs.

@MGatner

Copy link
Copy Markdown
Member

I won't repeat my arguments, the original PR is here with discussion: #4647

I would like to point out that after doing a deep dive on URI handling and bug fixes both @kenjis and I came to the same conclusion, independently. I think the problem is larger than credited and may indeed merit the potential confusion/clutter of an additional class.

@lonnieezell

Copy link
Copy Markdown
Member

After giving this a bit more thought, I think I'm ok with this on 2 conditions:

  1. It's designed for internal use within the request class and URL helper functions. Not intended for public use or really even documented. This avoids the confusion to end users, while still providing a "URI in Request is the source of truth" that @MGatner was looking for in the previous PR.
  2. It's saved for 5.0 (which we should be working on now....) since it's too big of a potential BC break.

@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from f65a55c to 72f76a6CompareFebruary 17, 2023 01:04
@iRedds

iRedds commented Feb 17, 2023

Copy link
Copy Markdown
Collaborator
$uri = $this->request->getUri();
echo (string) $uri; // "http://localhost:8888/ci431/public/test?a=b" → Okayecho$uri->getPath(); // "test" → NG. It should be "/ci431/public/test" when following PSR-7

And I think that such behavior corresponds to PSR.

// for http://localhost:8888/ci431/public/test?a=bURI::getPath(); // => /ci431/public/test// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)// Accordingly, the leading slash will determine whether the path is absolute or rootless// for http://localhost:8888/{base_path}/test?a=bURI::withPath('/xxx'); // http://localhost:8888/xxx?a=b// for http://localhost:8888/{base_path}/test?a=bURI::withPath('xxx'); // http://localhost:8888/{base_path}/xxx?a=b

php-fig/fig-standards#503

@kenjis

Copy link
Copy Markdown
MemberAuthor

What is {base_path} in this case? How do you define it?

// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)

@iRedds

Copy link
Copy Markdown
Collaborator

@kenjis app.baseURL = 'http://localhost:8888{/ci431/public/}' <- base path

@kenjis

Copy link
Copy Markdown
MemberAuthor

I don't get it.
How do you set it in PSR-7 URI object?

@iRedds

Copy link
Copy Markdown
Collaborator

There are no objects in PSR-7. Interfaces only. That is, mandatory public methods for PSR compliance.
A class implementing UriInterface should not be limited to UriInterface methods and may contain a method that sets base_path or base_url or whatever is needed for it to work properly.

@kenjis

Copy link
Copy Markdown
MemberAuthor

Many frameworks provide the ability to get the "base path," usually considered the path up to and including the front controller. As an example, if the application is served at http://example.com/b2b/index.php, and the current URI used to request it is http://example.com/b2b/index.php/customer/register, the functionality to retrieve the base path would return /b2b/index.php. This value can then be used by routers to strip that path segment prior to attempting a match.
https://www.php-fig.org/psr/psr-7/meta/#why-is-no-functionality-included-for-retrieving-the-base-path

 * If an HTTP path is intended to be host-relative rather than path-relative
* then it must begin with a slash ("/"). HTTP paths not starting with a slash
* are assumed to be relative to some base path known to the application or
* consumer.
...
*/
public function withPath($path);

https://www.php-fig.org/psr/psr-7/

This means like this?

  • if we call URI::withPath('foo/bar'), the path foo/bar is relative to some base path known to the application.
  • the new URI instance getPath() will return foo/bar?

@kenjis

Copy link
Copy Markdown
MemberAuthor
<?phprequire__DIR__ . '/vendor/autoload.php';
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
echo$uri . PHP_EOL; // http://localhost/ci4/foo/barecho$uri->getPath() . PHP_EOL; // /ci4/foo/bar

https://uri.thephpleague.com/uri/6.0/psr7/

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');

PHP Fatal error: Uncaught League\Uri\Exceptions\SyntaxError: If an authority is present the path must be empty or start with a /. in /.../league-uri/vendor/league/uri/src/Uri.php:921

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useSlim\Psr7\Factory\UriFactory;
$factory = newUriFactory();
$uri = $factory->createUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@kenjis

Copy link
Copy Markdown
MemberAuthor
useNyholm\Psr7\Uri;
$uri = newUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@iRedds

Copy link
Copy Markdown
Collaborator
  • the new URI instance getPath() will return foo/bar?

empty string

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great! I feel validated in the need for this given how much code is in SiteURI on top of URI. I appreciate your verbosity in naming variables and methods - it is easy to overlook pieces which has led to many bugs in the past. I think this will be a good step forward.

I assume the URL Helper methods get changed in the next PR? I haven't looked at that one yet...

Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php
Comment threadsystem/HTTP/URI.php Outdated
Comment threadsystem/HTTP/URI.php Outdated
@kenjis
kenjis merged commit 09f62eb into codeigniter4:4.4Jul 11, 2023
@kenjis
kenjis deleted the feat-SiteURL branch July 11, 2023 23:14
@kenjis

Copy link
Copy Markdown
MemberAuthor

@TimexPeachtree@MGatner Thank you for approvals.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancementPRs that improve existing functionalities

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants

@kenjis@michalsn@lonnieezell@MGatner@iRedds@samsonasik@TimexPeachtree
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat: add SiteURI class - #7252

Merged
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL
Jul 11, 2023
Merged

feat: add SiteURI class#7252
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL

Conversation

@kenjis

@kenjiskenjis commented Feb 14, 2023

Copy link
Copy Markdown
Member

Description
This PR is needed for #7123

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

  • add SiteURI class
    • The $routePath never starts with /.
    • If the path ends with /, the URI retains the trailing /.
    • getPath() returns the full URI path.
    • getRoutePath() returns the path relative to baseURL.

Related #5930, #7239, #7249, #7251

Checklist:

  • Securely signed commits
  • Component(s) with PHPDoc blocks, only if necessary or adds value
  • Unit testing, with >80% coverage
  • User guide updated
  • Conforms to style guide

@kenjiskenjis added enhancement PRs that improve existing functionalities 4.4 labels Feb 14, 2023
@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from 2d602ea to 87c90caCompareFebruary 14, 2023 08:48
Comment threadsystem/HTTP/SiteURI.php Outdated
@michalsn

Copy link
Copy Markdown
Member

Maybe this is a silly question, but... as I understand, this new class will bring full PSR-7 compatibility, right?

I don't see any related changes in the framework so we won't rely on it. The question is, who needs this class and for what?

Like... I saw your description:

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

But I'm afraid I don't fully understand the use cases.

@kenjis

kenjis commented Feb 15, 2023

Copy link
Copy Markdown
MemberAuthor

This PR only adds a new SiteURI class, and does not change the current framework behavior yet.

In the next PR(s), I will do:

  • add a factory to create the SiteURI instance for the current URL: feat: add SiteURIFactory #7256
  • set the SiteURI instance in the uri property of the Request
  • use the SiteURI instance when getting the current URL like current_url()

About compatibility with PSR-7, the URI class will be cleaner because site-related functions like baseURL, will be separated into the SiteURI class. And the URI class will be easier to change.

Finally, I think URI and SiteURL can be made fully compatible (and having some extended functions) with PSR-7.

@kenjiskenjis mentioned this pull request Feb 15, 2023
5 tasks

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am obviously in favor of this but I want to be sure we get reviews from @lonnieezell and @iRedds and anyone else who was opposed to the idea originally.

@lonnieezell

lonnieezell commented Feb 15, 2023

Copy link
Copy Markdown
Member

I was purposefully not commenting since my position was already known and it seemed I was overruled :)

I'm confused why we need a second class that does 99% of the same things as the URI class. The URI class is just for working with URIs in general, crafted to meet the RFC as best we could at the time. It seems like all other issues should be fixed where it's used, or the base class should be changed to support our needs.

The implementation itself is solid enough. Though if we're going to include it, we need docs and guidance on when to use which one.

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers. What is the point of this other then to throw confusion about which class people should use when? I figured it was to fix issues in how the framework was returning answers, but it doesn't seem like we're actually doing that.

@michalsn

Copy link
Copy Markdown
Member

I agree with @lonnieezell. I don't understand why we need a second class to handle URLs. Can somebody give me a clear example of where it will be useful?

AFAIK the only issue that we have now with the URI class is that it does not follow PSR-7 (it's something path related).

Also, if the goal for both classes is to follow the PSR-7, what will be the difference? Wouldn't it be better to see some additional methods added to the current class instead?

@kenjis

kenjis commented Feb 16, 2023

Copy link
Copy Markdown
MemberAuthor

I don't understand why we need a second class to handle URLs.

Because we have already two kinds of concept URI,
and if we have two classes, It is easier to understand for us.

  1. URI: a URI
  2. SiteURI: a URI for a CI4 app site.

SiteURI has its own properties like baseURL, indexPage and we cannot change the URI path
inside baseURL (subfolders). Only the URI path after indexPage does matter.

Now we are already confusing 1. and 2. So we have two kinds of URI segments for one SiteURL.
See #7123 (comment)

@kenjis

Copy link
Copy Markdown
MemberAuthor

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers.

This fix (and refactoring) will be long story. This PR is just the first one.
We will use the new class in all places after all. Please wait for incoming PRs.

@MGatner

Copy link
Copy Markdown
Member

I won't repeat my arguments, the original PR is here with discussion: #4647

I would like to point out that after doing a deep dive on URI handling and bug fixes both @kenjis and I came to the same conclusion, independently. I think the problem is larger than credited and may indeed merit the potential confusion/clutter of an additional class.

@lonnieezell

Copy link
Copy Markdown
Member

After giving this a bit more thought, I think I'm ok with this on 2 conditions:

  1. It's designed for internal use within the request class and URL helper functions. Not intended for public use or really even documented. This avoids the confusion to end users, while still providing a "URI in Request is the source of truth" that @MGatner was looking for in the previous PR.
  2. It's saved for 5.0 (which we should be working on now....) since it's too big of a potential BC break.

@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from f65a55c to 72f76a6CompareFebruary 17, 2023 01:04
@iRedds

iRedds commented Feb 17, 2023

Copy link
Copy Markdown
Collaborator
$uri = $this->request->getUri();
echo (string) $uri; // "http://localhost:8888/ci431/public/test?a=b" → Okayecho$uri->getPath(); // "test" → NG. It should be "/ci431/public/test" when following PSR-7

And I think that such behavior corresponds to PSR.

// for http://localhost:8888/ci431/public/test?a=bURI::getPath(); // => /ci431/public/test// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)// Accordingly, the leading slash will determine whether the path is absolute or rootless// for http://localhost:8888/{base_path}/test?a=bURI::withPath('/xxx'); // http://localhost:8888/xxx?a=b// for http://localhost:8888/{base_path}/test?a=bURI::withPath('xxx'); // http://localhost:8888/{base_path}/xxx?a=b

php-fig/fig-standards#503

@kenjis

Copy link
Copy Markdown
MemberAuthor

What is {base_path} in this case? How do you define it?

// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)

@iRedds

Copy link
Copy Markdown
Collaborator

@kenjis app.baseURL = 'http://localhost:8888{/ci431/public/}' <- base path

@kenjis

Copy link
Copy Markdown
MemberAuthor

I don't get it.
How do you set it in PSR-7 URI object?

@iRedds

Copy link
Copy Markdown
Collaborator

There are no objects in PSR-7. Interfaces only. That is, mandatory public methods for PSR compliance.
A class implementing UriInterface should not be limited to UriInterface methods and may contain a method that sets base_path or base_url or whatever is needed for it to work properly.

@kenjis

Copy link
Copy Markdown
MemberAuthor

Many frameworks provide the ability to get the "base path," usually considered the path up to and including the front controller. As an example, if the application is served at http://example.com/b2b/index.php, and the current URI used to request it is http://example.com/b2b/index.php/customer/register, the functionality to retrieve the base path would return /b2b/index.php. This value can then be used by routers to strip that path segment prior to attempting a match.
https://www.php-fig.org/psr/psr-7/meta/#why-is-no-functionality-included-for-retrieving-the-base-path

 * If an HTTP path is intended to be host-relative rather than path-relative
* then it must begin with a slash ("/"). HTTP paths not starting with a slash
* are assumed to be relative to some base path known to the application or
* consumer.
...
*/
public function withPath($path);

https://www.php-fig.org/psr/psr-7/

This means like this?

  • if we call URI::withPath('foo/bar'), the path foo/bar is relative to some base path known to the application.
  • the new URI instance getPath() will return foo/bar?

@kenjis

Copy link
Copy Markdown
MemberAuthor
<?phprequire__DIR__ . '/vendor/autoload.php';
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
echo$uri . PHP_EOL; // http://localhost/ci4/foo/barecho$uri->getPath() . PHP_EOL; // /ci4/foo/bar

https://uri.thephpleague.com/uri/6.0/psr7/

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');

PHP Fatal error: Uncaught League\Uri\Exceptions\SyntaxError: If an authority is present the path must be empty or start with a /. in /.../league-uri/vendor/league/uri/src/Uri.php:921

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useSlim\Psr7\Factory\UriFactory;
$factory = newUriFactory();
$uri = $factory->createUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@kenjis

Copy link
Copy Markdown
MemberAuthor
useNyholm\Psr7\Uri;
$uri = newUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@iRedds

Copy link
Copy Markdown
Collaborator
  • the new URI instance getPath() will return foo/bar?

empty string

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great! I feel validated in the need for this given how much code is in SiteURI on top of URI. I appreciate your verbosity in naming variables and methods - it is easy to overlook pieces which has led to many bugs in the past. I think this will be a good step forward.

I assume the URL Helper methods get changed in the next PR? I haven't looked at that one yet...

Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php
Comment threadsystem/HTTP/URI.php Outdated
Comment threadsystem/HTTP/URI.php Outdated
@kenjis
kenjis merged commit 09f62eb into codeigniter4:4.4Jul 11, 2023
@kenjis
kenjis deleted the feat-SiteURL branch July 11, 2023 23:14
@kenjis

Copy link
Copy Markdown
MemberAuthor

@TimexPeachtree@MGatner Thank you for approvals.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancementPRs that improve existing functionalities

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants

@kenjis@michalsn@lonnieezell@MGatner@iRedds@samsonasik@TimexPeachtree
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

feat: add SiteURI class - #7252

Merged
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL
Jul 11, 2023
Merged

feat: add SiteURI class#7252
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL

Conversation

@kenjis

@kenjiskenjis commented Feb 14, 2023

Copy link
Copy Markdown
Member

Description
This PR is needed for #7123

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

  • add SiteURI class
    • The $routePath never starts with /.
    • If the path ends with /, the URI retains the trailing /.
    • getPath() returns the full URI path.
    • getRoutePath() returns the path relative to baseURL.

Related #5930, #7239, #7249, #7251

Checklist:

  • Securely signed commits
  • Component(s) with PHPDoc blocks, only if necessary or adds value
  • Unit testing, with >80% coverage
  • User guide updated
  • Conforms to style guide

@kenjiskenjis added enhancement PRs that improve existing functionalities 4.4 labels Feb 14, 2023
@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from 2d602ea to 87c90caCompareFebruary 14, 2023 08:48
Comment threadsystem/HTTP/SiteURI.php Outdated
@michalsn

Copy link
Copy Markdown
Member

Maybe this is a silly question, but... as I understand, this new class will bring full PSR-7 compatibility, right?

I don't see any related changes in the framework so we won't rely on it. The question is, who needs this class and for what?

Like... I saw your description:

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

But I'm afraid I don't fully understand the use cases.

@kenjis

kenjis commented Feb 15, 2023

Copy link
Copy Markdown
MemberAuthor

This PR only adds a new SiteURI class, and does not change the current framework behavior yet.

In the next PR(s), I will do:

  • add a factory to create the SiteURI instance for the current URL: feat: add SiteURIFactory #7256
  • set the SiteURI instance in the uri property of the Request
  • use the SiteURI instance when getting the current URL like current_url()

About compatibility with PSR-7, the URI class will be cleaner because site-related functions like baseURL, will be separated into the SiteURI class. And the URI class will be easier to change.

Finally, I think URI and SiteURL can be made fully compatible (and having some extended functions) with PSR-7.

@kenjiskenjis mentioned this pull request Feb 15, 2023
5 tasks

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am obviously in favor of this but I want to be sure we get reviews from @lonnieezell and @iRedds and anyone else who was opposed to the idea originally.

@lonnieezell

lonnieezell commented Feb 15, 2023

Copy link
Copy Markdown
Member

I was purposefully not commenting since my position was already known and it seemed I was overruled :)

I'm confused why we need a second class that does 99% of the same things as the URI class. The URI class is just for working with URIs in general, crafted to meet the RFC as best we could at the time. It seems like all other issues should be fixed where it's used, or the base class should be changed to support our needs.

The implementation itself is solid enough. Though if we're going to include it, we need docs and guidance on when to use which one.

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers. What is the point of this other then to throw confusion about which class people should use when? I figured it was to fix issues in how the framework was returning answers, but it doesn't seem like we're actually doing that.

@michalsn

Copy link
Copy Markdown
Member

I agree with @lonnieezell. I don't understand why we need a second class to handle URLs. Can somebody give me a clear example of where it will be useful?

AFAIK the only issue that we have now with the URI class is that it does not follow PSR-7 (it's something path related).

Also, if the goal for both classes is to follow the PSR-7, what will be the difference? Wouldn't it be better to see some additional methods added to the current class instead?

@kenjis

kenjis commented Feb 16, 2023

Copy link
Copy Markdown
MemberAuthor

I don't understand why we need a second class to handle URLs.

Because we have already two kinds of concept URI,
and if we have two classes, It is easier to understand for us.

  1. URI: a URI
  2. SiteURI: a URI for a CI4 app site.

SiteURI has its own properties like baseURL, indexPage and we cannot change the URI path
inside baseURL (subfolders). Only the URI path after indexPage does matter.

Now we are already confusing 1. and 2. So we have two kinds of URI segments for one SiteURL.
See #7123 (comment)

@kenjis

Copy link
Copy Markdown
MemberAuthor

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers.

This fix (and refactoring) will be long story. This PR is just the first one.
We will use the new class in all places after all. Please wait for incoming PRs.

@MGatner

Copy link
Copy Markdown
Member

I won't repeat my arguments, the original PR is here with discussion: #4647

I would like to point out that after doing a deep dive on URI handling and bug fixes both @kenjis and I came to the same conclusion, independently. I think the problem is larger than credited and may indeed merit the potential confusion/clutter of an additional class.

@lonnieezell

Copy link
Copy Markdown
Member

After giving this a bit more thought, I think I'm ok with this on 2 conditions:

  1. It's designed for internal use within the request class and URL helper functions. Not intended for public use or really even documented. This avoids the confusion to end users, while still providing a "URI in Request is the source of truth" that @MGatner was looking for in the previous PR.
  2. It's saved for 5.0 (which we should be working on now....) since it's too big of a potential BC break.

@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from f65a55c to 72f76a6CompareFebruary 17, 2023 01:04
@iRedds

iRedds commented Feb 17, 2023

Copy link
Copy Markdown
Collaborator
$uri = $this->request->getUri();
echo (string) $uri; // "http://localhost:8888/ci431/public/test?a=b" → Okayecho$uri->getPath(); // "test" → NG. It should be "/ci431/public/test" when following PSR-7

And I think that such behavior corresponds to PSR.

// for http://localhost:8888/ci431/public/test?a=bURI::getPath(); // => /ci431/public/test// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)// Accordingly, the leading slash will determine whether the path is absolute or rootless// for http://localhost:8888/{base_path}/test?a=bURI::withPath('/xxx'); // http://localhost:8888/xxx?a=b// for http://localhost:8888/{base_path}/test?a=bURI::withPath('xxx'); // http://localhost:8888/{base_path}/xxx?a=b

php-fig/fig-standards#503

@kenjis

Copy link
Copy Markdown
MemberAuthor

What is {base_path} in this case? How do you define it?

// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)

@iRedds

Copy link
Copy Markdown
Collaborator

@kenjis app.baseURL = 'http://localhost:8888{/ci431/public/}' <- base path

@kenjis

Copy link
Copy Markdown
MemberAuthor

I don't get it.
How do you set it in PSR-7 URI object?

@iRedds

Copy link
Copy Markdown
Collaborator

There are no objects in PSR-7. Interfaces only. That is, mandatory public methods for PSR compliance.
A class implementing UriInterface should not be limited to UriInterface methods and may contain a method that sets base_path or base_url or whatever is needed for it to work properly.

@kenjis

Copy link
Copy Markdown
MemberAuthor

Many frameworks provide the ability to get the "base path," usually considered the path up to and including the front controller. As an example, if the application is served at http://example.com/b2b/index.php, and the current URI used to request it is http://example.com/b2b/index.php/customer/register, the functionality to retrieve the base path would return /b2b/index.php. This value can then be used by routers to strip that path segment prior to attempting a match.
https://www.php-fig.org/psr/psr-7/meta/#why-is-no-functionality-included-for-retrieving-the-base-path

 * If an HTTP path is intended to be host-relative rather than path-relative
* then it must begin with a slash ("/"). HTTP paths not starting with a slash
* are assumed to be relative to some base path known to the application or
* consumer.
...
*/
public function withPath($path);

https://www.php-fig.org/psr/psr-7/

This means like this?

  • if we call URI::withPath('foo/bar'), the path foo/bar is relative to some base path known to the application.
  • the new URI instance getPath() will return foo/bar?

@kenjis

Copy link
Copy Markdown
MemberAuthor
<?phprequire__DIR__ . '/vendor/autoload.php';
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
echo$uri . PHP_EOL; // http://localhost/ci4/foo/barecho$uri->getPath() . PHP_EOL; // /ci4/foo/bar

https://uri.thephpleague.com/uri/6.0/psr7/

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');

PHP Fatal error: Uncaught League\Uri\Exceptions\SyntaxError: If an authority is present the path must be empty or start with a /. in /.../league-uri/vendor/league/uri/src/Uri.php:921

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useSlim\Psr7\Factory\UriFactory;
$factory = newUriFactory();
$uri = $factory->createUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@kenjis

Copy link
Copy Markdown
MemberAuthor
useNyholm\Psr7\Uri;
$uri = newUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@iRedds

Copy link
Copy Markdown
Collaborator
  • the new URI instance getPath() will return foo/bar?

empty string

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great! I feel validated in the need for this given how much code is in SiteURI on top of URI. I appreciate your verbosity in naming variables and methods - it is easy to overlook pieces which has led to many bugs in the past. I think this will be a good step forward.

I assume the URL Helper methods get changed in the next PR? I haven't looked at that one yet...

Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php
Comment threadsystem/HTTP/URI.php Outdated
Comment threadsystem/HTTP/URI.php Outdated
@kenjis
kenjis merged commit 09f62eb into codeigniter4:4.4Jul 11, 2023
@kenjis
kenjis deleted the feat-SiteURL branch July 11, 2023 23:14
@kenjis

Copy link
Copy Markdown
MemberAuthor

@TimexPeachtree@MGatner Thank you for approvals.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancementPRs that improve existing functionalities

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants

@kenjis@michalsn@lonnieezell@MGatner@iRedds@samsonasik@TimexPeachtree
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat: add SiteURI class - #7252

Merged
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL
Jul 11, 2023
Merged

feat: add SiteURI class#7252
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL

Conversation

@kenjis

@kenjiskenjis commented Feb 14, 2023

Copy link
Copy Markdown
Member

Description
This PR is needed for #7123

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

  • add SiteURI class
    • The $routePath never starts with /.
    • If the path ends with /, the URI retains the trailing /.
    • getPath() returns the full URI path.
    • getRoutePath() returns the path relative to baseURL.

Related #5930, #7239, #7249, #7251

Checklist:

  • Securely signed commits
  • Component(s) with PHPDoc blocks, only if necessary or adds value
  • Unit testing, with >80% coverage
  • User guide updated
  • Conforms to style guide

@kenjiskenjis added enhancement PRs that improve existing functionalities 4.4 labels Feb 14, 2023
@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from 2d602ea to 87c90caCompareFebruary 14, 2023 08:48
Comment threadsystem/HTTP/SiteURI.php Outdated
@michalsn

Copy link
Copy Markdown
Member

Maybe this is a silly question, but... as I understand, this new class will bring full PSR-7 compatibility, right?

I don't see any related changes in the framework so we won't rely on it. The question is, who needs this class and for what?

Like... I saw your description:

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

But I'm afraid I don't fully understand the use cases.

@kenjis

kenjis commented Feb 15, 2023

Copy link
Copy Markdown
MemberAuthor

This PR only adds a new SiteURI class, and does not change the current framework behavior yet.

In the next PR(s), I will do:

  • add a factory to create the SiteURI instance for the current URL: feat: add SiteURIFactory #7256
  • set the SiteURI instance in the uri property of the Request
  • use the SiteURI instance when getting the current URL like current_url()

About compatibility with PSR-7, the URI class will be cleaner because site-related functions like baseURL, will be separated into the SiteURI class. And the URI class will be easier to change.

Finally, I think URI and SiteURL can be made fully compatible (and having some extended functions) with PSR-7.

@kenjiskenjis mentioned this pull request Feb 15, 2023
5 tasks

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am obviously in favor of this but I want to be sure we get reviews from @lonnieezell and @iRedds and anyone else who was opposed to the idea originally.

@lonnieezell

lonnieezell commented Feb 15, 2023

Copy link
Copy Markdown
Member

I was purposefully not commenting since my position was already known and it seemed I was overruled :)

I'm confused why we need a second class that does 99% of the same things as the URI class. The URI class is just for working with URIs in general, crafted to meet the RFC as best we could at the time. It seems like all other issues should be fixed where it's used, or the base class should be changed to support our needs.

The implementation itself is solid enough. Though if we're going to include it, we need docs and guidance on when to use which one.

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers. What is the point of this other then to throw confusion about which class people should use when? I figured it was to fix issues in how the framework was returning answers, but it doesn't seem like we're actually doing that.

@michalsn

Copy link
Copy Markdown
Member

I agree with @lonnieezell. I don't understand why we need a second class to handle URLs. Can somebody give me a clear example of where it will be useful?

AFAIK the only issue that we have now with the URI class is that it does not follow PSR-7 (it's something path related).

Also, if the goal for both classes is to follow the PSR-7, what will be the difference? Wouldn't it be better to see some additional methods added to the current class instead?

@kenjis

kenjis commented Feb 16, 2023

Copy link
Copy Markdown
MemberAuthor

I don't understand why we need a second class to handle URLs.

Because we have already two kinds of concept URI,
and if we have two classes, It is easier to understand for us.

  1. URI: a URI
  2. SiteURI: a URI for a CI4 app site.

SiteURI has its own properties like baseURL, indexPage and we cannot change the URI path
inside baseURL (subfolders). Only the URI path after indexPage does matter.

Now we are already confusing 1. and 2. So we have two kinds of URI segments for one SiteURL.
See #7123 (comment)

@kenjis

Copy link
Copy Markdown
MemberAuthor

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers.

This fix (and refactoring) will be long story. This PR is just the first one.
We will use the new class in all places after all. Please wait for incoming PRs.

@MGatner

Copy link
Copy Markdown
Member

I won't repeat my arguments, the original PR is here with discussion: #4647

I would like to point out that after doing a deep dive on URI handling and bug fixes both @kenjis and I came to the same conclusion, independently. I think the problem is larger than credited and may indeed merit the potential confusion/clutter of an additional class.

@lonnieezell

Copy link
Copy Markdown
Member

After giving this a bit more thought, I think I'm ok with this on 2 conditions:

  1. It's designed for internal use within the request class and URL helper functions. Not intended for public use or really even documented. This avoids the confusion to end users, while still providing a "URI in Request is the source of truth" that @MGatner was looking for in the previous PR.
  2. It's saved for 5.0 (which we should be working on now....) since it's too big of a potential BC break.

@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from f65a55c to 72f76a6CompareFebruary 17, 2023 01:04
@iRedds

iRedds commented Feb 17, 2023

Copy link
Copy Markdown
Collaborator
$uri = $this->request->getUri();
echo (string) $uri; // "http://localhost:8888/ci431/public/test?a=b" → Okayecho$uri->getPath(); // "test" → NG. It should be "/ci431/public/test" when following PSR-7

And I think that such behavior corresponds to PSR.

// for http://localhost:8888/ci431/public/test?a=bURI::getPath(); // => /ci431/public/test// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)// Accordingly, the leading slash will determine whether the path is absolute or rootless// for http://localhost:8888/{base_path}/test?a=bURI::withPath('/xxx'); // http://localhost:8888/xxx?a=b// for http://localhost:8888/{base_path}/test?a=bURI::withPath('xxx'); // http://localhost:8888/{base_path}/xxx?a=b

php-fig/fig-standards#503

@kenjis

Copy link
Copy Markdown
MemberAuthor

What is {base_path} in this case? How do you define it?

// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)

@iRedds

Copy link
Copy Markdown
Collaborator

@kenjis app.baseURL = 'http://localhost:8888{/ci431/public/}' <- base path

@kenjis

Copy link
Copy Markdown
MemberAuthor

I don't get it.
How do you set it in PSR-7 URI object?

@iRedds

Copy link
Copy Markdown
Collaborator

There are no objects in PSR-7. Interfaces only. That is, mandatory public methods for PSR compliance.
A class implementing UriInterface should not be limited to UriInterface methods and may contain a method that sets base_path or base_url or whatever is needed for it to work properly.

@kenjis

Copy link
Copy Markdown
MemberAuthor

Many frameworks provide the ability to get the "base path," usually considered the path up to and including the front controller. As an example, if the application is served at http://example.com/b2b/index.php, and the current URI used to request it is http://example.com/b2b/index.php/customer/register, the functionality to retrieve the base path would return /b2b/index.php. This value can then be used by routers to strip that path segment prior to attempting a match.
https://www.php-fig.org/psr/psr-7/meta/#why-is-no-functionality-included-for-retrieving-the-base-path

 * If an HTTP path is intended to be host-relative rather than path-relative
* then it must begin with a slash ("/"). HTTP paths not starting with a slash
* are assumed to be relative to some base path known to the application or
* consumer.
...
*/
public function withPath($path);

https://www.php-fig.org/psr/psr-7/

This means like this?

  • if we call URI::withPath('foo/bar'), the path foo/bar is relative to some base path known to the application.
  • the new URI instance getPath() will return foo/bar?

@kenjis

Copy link
Copy Markdown
MemberAuthor
<?phprequire__DIR__ . '/vendor/autoload.php';
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
echo$uri . PHP_EOL; // http://localhost/ci4/foo/barecho$uri->getPath() . PHP_EOL; // /ci4/foo/bar

https://uri.thephpleague.com/uri/6.0/psr7/

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');

PHP Fatal error: Uncaught League\Uri\Exceptions\SyntaxError: If an authority is present the path must be empty or start with a /. in /.../league-uri/vendor/league/uri/src/Uri.php:921

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useSlim\Psr7\Factory\UriFactory;
$factory = newUriFactory();
$uri = $factory->createUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@kenjis

Copy link
Copy Markdown
MemberAuthor
useNyholm\Psr7\Uri;
$uri = newUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@iRedds

Copy link
Copy Markdown
Collaborator
  • the new URI instance getPath() will return foo/bar?

empty string

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great! I feel validated in the need for this given how much code is in SiteURI on top of URI. I appreciate your verbosity in naming variables and methods - it is easy to overlook pieces which has led to many bugs in the past. I think this will be a good step forward.

I assume the URL Helper methods get changed in the next PR? I haven't looked at that one yet...

Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php
Comment threadsystem/HTTP/URI.php Outdated
Comment threadsystem/HTTP/URI.php Outdated
@kenjis
kenjis merged commit 09f62eb into codeigniter4:4.4Jul 11, 2023
@kenjis
kenjis deleted the feat-SiteURL branch July 11, 2023 23:14
@kenjis

Copy link
Copy Markdown
MemberAuthor

@TimexPeachtree@MGatner Thank you for approvals.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancementPRs that improve existing functionalities

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants

@kenjis@michalsn@lonnieezell@MGatner@iRedds@samsonasik@TimexPeachtree
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat: add SiteURI class - #7252

Merged
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL
Jul 11, 2023
Merged

feat: add SiteURI class#7252
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL

Conversation

@kenjis

@kenjiskenjis commented Feb 14, 2023

Copy link
Copy Markdown
Member

Description
This PR is needed for #7123

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

  • add SiteURI class
    • The $routePath never starts with /.
    • If the path ends with /, the URI retains the trailing /.
    • getPath() returns the full URI path.
    • getRoutePath() returns the path relative to baseURL.

Related #5930, #7239, #7249, #7251

Checklist:

  • Securely signed commits
  • Component(s) with PHPDoc blocks, only if necessary or adds value
  • Unit testing, with >80% coverage
  • User guide updated
  • Conforms to style guide

@kenjiskenjis added enhancement PRs that improve existing functionalities 4.4 labels Feb 14, 2023
@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from 2d602ea to 87c90caCompareFebruary 14, 2023 08:48
Comment threadsystem/HTTP/SiteURI.php Outdated
@michalsn

Copy link
Copy Markdown
Member

Maybe this is a silly question, but... as I understand, this new class will bring full PSR-7 compatibility, right?

I don't see any related changes in the framework so we won't rely on it. The question is, who needs this class and for what?

Like... I saw your description:

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

But I'm afraid I don't fully understand the use cases.

@kenjis

kenjis commented Feb 15, 2023

Copy link
Copy Markdown
MemberAuthor

This PR only adds a new SiteURI class, and does not change the current framework behavior yet.

In the next PR(s), I will do:

  • add a factory to create the SiteURI instance for the current URL: feat: add SiteURIFactory #7256
  • set the SiteURI instance in the uri property of the Request
  • use the SiteURI instance when getting the current URL like current_url()

About compatibility with PSR-7, the URI class will be cleaner because site-related functions like baseURL, will be separated into the SiteURI class. And the URI class will be easier to change.

Finally, I think URI and SiteURL can be made fully compatible (and having some extended functions) with PSR-7.

@kenjiskenjis mentioned this pull request Feb 15, 2023
5 tasks

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am obviously in favor of this but I want to be sure we get reviews from @lonnieezell and @iRedds and anyone else who was opposed to the idea originally.

@lonnieezell

lonnieezell commented Feb 15, 2023

Copy link
Copy Markdown
Member

I was purposefully not commenting since my position was already known and it seemed I was overruled :)

I'm confused why we need a second class that does 99% of the same things as the URI class. The URI class is just for working with URIs in general, crafted to meet the RFC as best we could at the time. It seems like all other issues should be fixed where it's used, or the base class should be changed to support our needs.

The implementation itself is solid enough. Though if we're going to include it, we need docs and guidance on when to use which one.

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers. What is the point of this other then to throw confusion about which class people should use when? I figured it was to fix issues in how the framework was returning answers, but it doesn't seem like we're actually doing that.

@michalsn

Copy link
Copy Markdown
Member

I agree with @lonnieezell. I don't understand why we need a second class to handle URLs. Can somebody give me a clear example of where it will be useful?

AFAIK the only issue that we have now with the URI class is that it does not follow PSR-7 (it's something path related).

Also, if the goal for both classes is to follow the PSR-7, what will be the difference? Wouldn't it be better to see some additional methods added to the current class instead?

@kenjis

kenjis commented Feb 16, 2023

Copy link
Copy Markdown
MemberAuthor

I don't understand why we need a second class to handle URLs.

Because we have already two kinds of concept URI,
and if we have two classes, It is easier to understand for us.

  1. URI: a URI
  2. SiteURI: a URI for a CI4 app site.

SiteURI has its own properties like baseURL, indexPage and we cannot change the URI path
inside baseURL (subfolders). Only the URI path after indexPage does matter.

Now we are already confusing 1. and 2. So we have two kinds of URI segments for one SiteURL.
See #7123 (comment)

@kenjis

Copy link
Copy Markdown
MemberAuthor

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers.

This fix (and refactoring) will be long story. This PR is just the first one.
We will use the new class in all places after all. Please wait for incoming PRs.

@MGatner

Copy link
Copy Markdown
Member

I won't repeat my arguments, the original PR is here with discussion: #4647

I would like to point out that after doing a deep dive on URI handling and bug fixes both @kenjis and I came to the same conclusion, independently. I think the problem is larger than credited and may indeed merit the potential confusion/clutter of an additional class.

@lonnieezell

Copy link
Copy Markdown
Member

After giving this a bit more thought, I think I'm ok with this on 2 conditions:

  1. It's designed for internal use within the request class and URL helper functions. Not intended for public use or really even documented. This avoids the confusion to end users, while still providing a "URI in Request is the source of truth" that @MGatner was looking for in the previous PR.
  2. It's saved for 5.0 (which we should be working on now....) since it's too big of a potential BC break.

@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from f65a55c to 72f76a6CompareFebruary 17, 2023 01:04
@iRedds

iRedds commented Feb 17, 2023

Copy link
Copy Markdown
Collaborator
$uri = $this->request->getUri();
echo (string) $uri; // "http://localhost:8888/ci431/public/test?a=b" → Okayecho$uri->getPath(); // "test" → NG. It should be "/ci431/public/test" when following PSR-7

And I think that such behavior corresponds to PSR.

// for http://localhost:8888/ci431/public/test?a=bURI::getPath(); // => /ci431/public/test// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)// Accordingly, the leading slash will determine whether the path is absolute or rootless// for http://localhost:8888/{base_path}/test?a=bURI::withPath('/xxx'); // http://localhost:8888/xxx?a=b// for http://localhost:8888/{base_path}/test?a=bURI::withPath('xxx'); // http://localhost:8888/{base_path}/xxx?a=b

php-fig/fig-standards#503

@kenjis

Copy link
Copy Markdown
MemberAuthor

What is {base_path} in this case? How do you define it?

// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)

@iRedds

Copy link
Copy Markdown
Collaborator

@kenjis app.baseURL = 'http://localhost:8888{/ci431/public/}' <- base path

@kenjis

Copy link
Copy Markdown
MemberAuthor

I don't get it.
How do you set it in PSR-7 URI object?

@iRedds

Copy link
Copy Markdown
Collaborator

There are no objects in PSR-7. Interfaces only. That is, mandatory public methods for PSR compliance.
A class implementing UriInterface should not be limited to UriInterface methods and may contain a method that sets base_path or base_url or whatever is needed for it to work properly.

@kenjis

Copy link
Copy Markdown
MemberAuthor

Many frameworks provide the ability to get the "base path," usually considered the path up to and including the front controller. As an example, if the application is served at http://example.com/b2b/index.php, and the current URI used to request it is http://example.com/b2b/index.php/customer/register, the functionality to retrieve the base path would return /b2b/index.php. This value can then be used by routers to strip that path segment prior to attempting a match.
https://www.php-fig.org/psr/psr-7/meta/#why-is-no-functionality-included-for-retrieving-the-base-path

 * If an HTTP path is intended to be host-relative rather than path-relative
* then it must begin with a slash ("/"). HTTP paths not starting with a slash
* are assumed to be relative to some base path known to the application or
* consumer.
...
*/
public function withPath($path);

https://www.php-fig.org/psr/psr-7/

This means like this?

  • if we call URI::withPath('foo/bar'), the path foo/bar is relative to some base path known to the application.
  • the new URI instance getPath() will return foo/bar?

@kenjis

Copy link
Copy Markdown
MemberAuthor
<?phprequire__DIR__ . '/vendor/autoload.php';
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
echo$uri . PHP_EOL; // http://localhost/ci4/foo/barecho$uri->getPath() . PHP_EOL; // /ci4/foo/bar

https://uri.thephpleague.com/uri/6.0/psr7/

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');

PHP Fatal error: Uncaught League\Uri\Exceptions\SyntaxError: If an authority is present the path must be empty or start with a /. in /.../league-uri/vendor/league/uri/src/Uri.php:921

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useSlim\Psr7\Factory\UriFactory;
$factory = newUriFactory();
$uri = $factory->createUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@kenjis

Copy link
Copy Markdown
MemberAuthor
useNyholm\Psr7\Uri;
$uri = newUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@iRedds

Copy link
Copy Markdown
Collaborator
  • the new URI instance getPath() will return foo/bar?

empty string

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great! I feel validated in the need for this given how much code is in SiteURI on top of URI. I appreciate your verbosity in naming variables and methods - it is easy to overlook pieces which has led to many bugs in the past. I think this will be a good step forward.

I assume the URL Helper methods get changed in the next PR? I haven't looked at that one yet...

Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php
Comment threadsystem/HTTP/URI.php Outdated
Comment threadsystem/HTTP/URI.php Outdated
@kenjis
kenjis merged commit 09f62eb into codeigniter4:4.4Jul 11, 2023
@kenjis
kenjis deleted the feat-SiteURL branch July 11, 2023 23:14
@kenjis

Copy link
Copy Markdown
MemberAuthor

@TimexPeachtree@MGatner Thank you for approvals.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancementPRs that improve existing functionalities

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants

@kenjis@michalsn@lonnieezell@MGatner@iRedds@samsonasik@TimexPeachtree
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

feat: add SiteURI class - #7252

Merged
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL
Jul 11, 2023
Merged

feat: add SiteURI class#7252
kenjis merged 31 commits into
codeigniter4:4.4from
kenjis:feat-SiteURL

Conversation

@kenjis

@kenjiskenjis commented Feb 14, 2023

Copy link
Copy Markdown
Member

Description
This PR is needed for #7123

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

  • add SiteURI class
    • The $routePath never starts with /.
    • If the path ends with /, the URI retains the trailing /.
    • getPath() returns the full URI path.
    • getRoutePath() returns the path relative to baseURL.

Related #5930, #7239, #7249, #7251

Checklist:

  • Securely signed commits
  • Component(s) with PHPDoc blocks, only if necessary or adds value
  • Unit testing, with >80% coverage
  • User guide updated
  • Conforms to style guide

@kenjiskenjis added enhancement PRs that improve existing functionalities 4.4 labels Feb 14, 2023
@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from 2d602ea to 87c90caCompareFebruary 14, 2023 08:48
Comment threadsystem/HTTP/SiteURI.php Outdated
@michalsn

Copy link
Copy Markdown
Member

Maybe this is a silly question, but... as I understand, this new class will bring full PSR-7 compatibility, right?

I don't see any related changes in the framework so we won't rely on it. The question is, who needs this class and for what?

Like... I saw your description:

We need two URI classes. One for general purpose URI class, and the other is for URI of the app site.

But I'm afraid I don't fully understand the use cases.

@kenjis

kenjis commented Feb 15, 2023

Copy link
Copy Markdown
MemberAuthor

This PR only adds a new SiteURI class, and does not change the current framework behavior yet.

In the next PR(s), I will do:

  • add a factory to create the SiteURI instance for the current URL: feat: add SiteURIFactory #7256
  • set the SiteURI instance in the uri property of the Request
  • use the SiteURI instance when getting the current URL like current_url()

About compatibility with PSR-7, the URI class will be cleaner because site-related functions like baseURL, will be separated into the SiteURI class. And the URI class will be easier to change.

Finally, I think URI and SiteURL can be made fully compatible (and having some extended functions) with PSR-7.

@kenjiskenjis mentioned this pull request Feb 15, 2023
5 tasks

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am obviously in favor of this but I want to be sure we get reviews from @lonnieezell and @iRedds and anyone else who was opposed to the idea originally.

@lonnieezell

lonnieezell commented Feb 15, 2023

Copy link
Copy Markdown
Member

I was purposefully not commenting since my position was already known and it seemed I was overruled :)

I'm confused why we need a second class that does 99% of the same things as the URI class. The URI class is just for working with URIs in general, crafted to meet the RFC as best we could at the time. It seems like all other issues should be fixed where it's used, or the base class should be changed to support our needs.

The implementation itself is solid enough. Though if we're going to include it, we need docs and guidance on when to use which one.

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers. What is the point of this other then to throw confusion about which class people should use when? I figured it was to fix issues in how the framework was returning answers, but it doesn't seem like we're actually doing that.

@michalsn

Copy link
Copy Markdown
Member

I agree with @lonnieezell. I don't understand why we need a second class to handle URLs. Can somebody give me a clear example of where it will be useful?

AFAIK the only issue that we have now with the URI class is that it does not follow PSR-7 (it's something path related).

Also, if the goal for both classes is to follow the PSR-7, what will be the difference? Wouldn't it be better to see some additional methods added to the current class instead?

@kenjis

kenjis commented Feb 16, 2023

Copy link
Copy Markdown
MemberAuthor

I don't understand why we need a second class to handle URLs.

Because we have already two kinds of concept URI,
and if we have two classes, It is easier to understand for us.

  1. URI: a URI
  2. SiteURI: a URI for a CI4 app site.

SiteURI has its own properties like baseURL, indexPage and we cannot change the URI path
inside baseURL (subfolders). Only the URI path after indexPage does matter.

Now we are already confusing 1. and 2. So we have two kinds of URI segments for one SiteURL.
See #7123 (comment)

@kenjis

Copy link
Copy Markdown
MemberAuthor

It seems strange to me to make this new class and we're not using it ourselves in IncomingRequest or the URL helpers.

This fix (and refactoring) will be long story. This PR is just the first one.
We will use the new class in all places after all. Please wait for incoming PRs.

@MGatner

Copy link
Copy Markdown
Member

I won't repeat my arguments, the original PR is here with discussion: #4647

I would like to point out that after doing a deep dive on URI handling and bug fixes both @kenjis and I came to the same conclusion, independently. I think the problem is larger than credited and may indeed merit the potential confusion/clutter of an additional class.

@lonnieezell

Copy link
Copy Markdown
Member

After giving this a bit more thought, I think I'm ok with this on 2 conditions:

  1. It's designed for internal use within the request class and URL helper functions. Not intended for public use or really even documented. This avoids the confusion to end users, while still providing a "URI in Request is the source of truth" that @MGatner was looking for in the previous PR.
  2. It's saved for 5.0 (which we should be working on now....) since it's too big of a potential BC break.

@kenjis
kenjisforce-pushed the feat-SiteURL branch 2 times, most recently from f65a55c to 72f76a6CompareFebruary 17, 2023 01:04
@iRedds

iRedds commented Feb 17, 2023

Copy link
Copy Markdown
Collaborator
$uri = $this->request->getUri();
echo (string) $uri; // "http://localhost:8888/ci431/public/test?a=b" → Okayecho$uri->getPath(); // "test" → NG. It should be "/ci431/public/test" when following PSR-7

And I think that such behavior corresponds to PSR.

// for http://localhost:8888/ci431/public/test?a=bURI::getPath(); // => /ci431/public/test// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)// Accordingly, the leading slash will determine whether the path is absolute or rootless// for http://localhost:8888/{base_path}/test?a=bURI::withPath('/xxx'); // http://localhost:8888/xxx?a=b// for http://localhost:8888/{base_path}/test?a=bURI::withPath('xxx'); // http://localhost:8888/{base_path}/xxx?a=b

php-fig/fig-standards#503

@kenjis

Copy link
Copy Markdown
MemberAuthor

What is {base_path} in this case? How do you define it?

// for http://localhost:8888/{base_path}/test?a=bURI::getPath(); // => test (without leading slash, as an indicator that the base path is being used.)

@iRedds

Copy link
Copy Markdown
Collaborator

@kenjis app.baseURL = 'http://localhost:8888{/ci431/public/}' <- base path

@kenjis

Copy link
Copy Markdown
MemberAuthor

I don't get it.
How do you set it in PSR-7 URI object?

@iRedds

Copy link
Copy Markdown
Collaborator

There are no objects in PSR-7. Interfaces only. That is, mandatory public methods for PSR compliance.
A class implementing UriInterface should not be limited to UriInterface methods and may contain a method that sets base_path or base_url or whatever is needed for it to work properly.

@kenjis

Copy link
Copy Markdown
MemberAuthor

Many frameworks provide the ability to get the "base path," usually considered the path up to and including the front controller. As an example, if the application is served at http://example.com/b2b/index.php, and the current URI used to request it is http://example.com/b2b/index.php/customer/register, the functionality to retrieve the base path would return /b2b/index.php. This value can then be used by routers to strip that path segment prior to attempting a match.
https://www.php-fig.org/psr/psr-7/meta/#why-is-no-functionality-included-for-retrieving-the-base-path

 * If an HTTP path is intended to be host-relative rather than path-relative
* then it must begin with a slash ("/"). HTTP paths not starting with a slash
* are assumed to be relative to some base path known to the application or
* consumer.
...
*/
public function withPath($path);

https://www.php-fig.org/psr/psr-7/

This means like this?

  • if we call URI::withPath('foo/bar'), the path foo/bar is relative to some base path known to the application.
  • the new URI instance getPath() will return foo/bar?

@kenjis

Copy link
Copy Markdown
MemberAuthor
<?phprequire__DIR__ . '/vendor/autoload.php';
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
echo$uri . PHP_EOL; // http://localhost/ci4/foo/barecho$uri->getPath() . PHP_EOL; // /ci4/foo/bar

https://uri.thephpleague.com/uri/6.0/psr7/

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useLeague\Uri\Http;
$uri = Http::createFromBaseUri('foo/bar', 'http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');

PHP Fatal error: Uncaught League\Uri\Exceptions\SyntaxError: If an authority is present the path must be empty or start with a /. in /.../league-uri/vendor/league/uri/src/Uri.php:921

@kenjis

kenjis commented Feb 17, 2023

Copy link
Copy Markdown
MemberAuthor
useSlim\Psr7\Factory\UriFactory;
$factory = newUriFactory();
$uri = $factory->createUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@kenjis

Copy link
Copy Markdown
MemberAuthor
useNyholm\Psr7\Uri;
$uri = newUri('http://localhost/ci4/');
$uri2 = $uri->withPath('controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // controller/method$uri2 = $uri->withPath('/controller/method');
echo$uri2 . PHP_EOL; // http://localhost/controller/methodecho$uri2->getPath() . PHP_EOL; // /controller/method

@iRedds

Copy link
Copy Markdown
Collaborator
  • the new URI instance getPath() will return foo/bar?

empty string

@MGatnerMGatner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great! I feel validated in the need for this given how much code is in SiteURI on top of URI. I appreciate your verbosity in naming variables and methods - it is easy to overlook pieces which has led to many bugs in the past. I think this will be a good step forward.

I assume the URL Helper methods get changed in the next PR? I haven't looked at that one yet...

Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php Outdated
Comment threadsystem/HTTP/SiteURI.php
Comment threadsystem/HTTP/URI.php Outdated
Comment threadsystem/HTTP/URI.php Outdated
@kenjis
kenjis merged commit 09f62eb into codeigniter4:4.4Jul 11, 2023
@kenjis
kenjis deleted the feat-SiteURL branch July 11, 2023 23:14
@kenjis

Copy link
Copy Markdown
MemberAuthor

@TimexPeachtree@MGatner Thank you for approvals.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancementPRs that improve existing functionalities

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants

@kenjis@michalsn@lonnieezell@MGatner@iRedds@samsonasik@TimexPeachtree