Problem/Motivation
Given a namespace or class name (e.g., Drupal\Component\Foo\Bar, Drupal\Foo\Bar, Drupal\foo\Bar, or Foo\Bar), how do you know if it corresponds to a name within a Drupal extension's namespace (i.e., Drupal\$module as added in DrupalKernel::getModuleNamespacesPsr4() or Drupal\$theme as added in ThemeHandler::addTheme())?
A use-case for wanting to know this came up in #3120096: Support contrib database driver directories in a fixed location in a module, where given a Drupal database driver's namespace we want to know if it's within the namespace of a module (as opposed to within Drupal\Driver or Drupal\Core or elsewhere).
Proposed resolution
Add a public static method Extension::isWithinExtensionNamespace($namespace_or_class_name) (TBD: discuss name of method, name of parameter, and if it belongs in the Extension class or elsewhere).
Option 1
Implement the logic based on whether the second-level namespace is all lowercase, as extension names are expected to be. This distinguishes extensions from other kinds of things that can occupy the second-level namespace, such as "Core" and "Component", and reserves the ability to arbitrarily add more non-extension namespaces within Drupal\ so long as they start with an uppercase letter.
Option 2
Since PHP namespaces are resolved in a case-insensitive way, don't rely on case, and instead hard-code a list of names that are not extensions. This needs to include "Component", "Core", "Driver", and possibly others. Assume that everything else is an extension name, which means no one outside of Drupal core can invent new names within Drupal\ that don't correspond to what Drupal defines as an extension: a module, theme, theme engine, or profile.
Comments
Comment #2
effulgentsia commentedComment #3
effulgentsia commentedComment #4
alexpottRepeating some of my comment on #3120096-118: Support contrib database driver directories in a fixed location in a module because it's relevant.
I think before we add this we should identify at least one place in core that requires this functionality.
Comment #5
alexpottLooking for
preg_match.*Drupalin core...corewhen a plugin is located in \Drupal\Core\...The only instances of exploding on
\\seem to be in tests and not to do with modules.I'm not sure that adding an API is worth it. However if it is I think creating a DrupalNamespace value object is the way to go. The constructor should take the namespace string and error if it doesn't start with Drupal\. And it should have methods like getProvider() and isModule() etc...
Comment #12
nicxvan commentedPostponing because I agree with 4 and 5 and in 6 years there doesn't seem to be any new use cases identified.
I'll leave this open for a bit in case I'm missing something.
Comment #13
nicxvan commentedI think this is safe to close at this point, if we decide it's needed later we can always reopen our create a new issue.