PluginBase: added getResourceFolder() and getResourcePath(), deprecate getResource() (#5961)

This is a step towards #5958.

While it's not actually necessary to add these functions (since people could just use getFile() . "/resources/whatever.yml" instead), this helps preserve the convention of using the `resources` folder, which might be helpful for external tools.

As an example:
stream_get_contents($this->getResource("lang/eng.ini"));
(which is actually incorrect, since it leaks a resource)
can now be replaced by
file_get_contents($this->getResourcePath("lang/eng.ini"));
quite trivially.

getResourceFolder() can be used with scandir() to enumerate resources instead of using getResources(), although getResources() still provides utility in the relativized resource paths.
This commit is contained in:
Dylan T 2023-08-09 16:09:16 +01:00 committed by GitHub
parent 447f061566
commit 97700636c6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -50,6 +50,8 @@ use const DIRECTORY_SEPARATOR;
abstract class PluginBase implements Plugin, CommandExecutor{
private bool $isEnabled = false;
private string $resourceFolder;
private ?Config $config = null;
private string $configFile;
@ -67,6 +69,8 @@ abstract class PluginBase implements Plugin, CommandExecutor{
$this->dataFolder = rtrim($dataFolder, "/" . DIRECTORY_SEPARATOR) . "/";
//TODO: this is accessed externally via reflection, not unused
$this->file = rtrim($file, "/" . DIRECTORY_SEPARATOR) . "/";
$this->resourceFolder = Path::join($this->file, "resources") . "/";
$this->configFile = Path::join($this->dataFolder, "config.yml");
$prefix = $this->getDescription()->getPrefix();
@ -209,6 +213,27 @@ abstract class PluginBase implements Plugin, CommandExecutor{
}
/**
* Returns the path to the folder where the plugin's embedded resource files are usually located.
* Note: This is NOT the same as the data folder. The files in this folder should be considered read-only.
*/
public function getResourceFolder() : string{
return $this->resourceFolder;
}
/**
* Returns the full path to a data file in the plugin's resources folder.
* This path can be used with standard PHP functions like fopen() or file_get_contents().
*
* Note: Any path returned by this function should be considered READ-ONLY.
*/
public function getResourcePath(string $filename) : string{
return Path::join($this->getResourceFolder(), $filename);
}
/**
* @deprecated Prefer using standard PHP functions with {@link PluginBase::getResourcePath()}, like
* file_get_contents() or fopen().
*
* Gets an embedded resource on the plugin file.
* WARNING: You must close the resource given using fclose()
*