PHP - get defined constants for a given namespace

I have a set of classes for data storage. It currently have a working connector for Google Drive, Dropbox, Box, FTP and local connection. I have designed this to construct a file manager where a client can manage multiple data storage sources.

Here comes my question. Currently, my implementation of the addConnection() method is the following:

// addConnection - adds a storage connection to the storage manager
public function addConnection($service, $credentials) {
    if (!empty($service) && !empty($credentials)) {
        if (in_array($service, [Connectors\Box, Connectors\Dropbox, Connectors\FTP, Connectors\GoogleDrive, Connectors\Local], true)) {
            // rest goes here...
        }
    }
}

I have my constants in a separate namespace like this:

namespace Services\Storage\Connectors {
    const Box = "Box";
    const Dropbox = "Dropbox";
    const FTP = "FTP";
    const GoogleDrive = "GoogleDrive";
    const Local = "Local";
}

Is there a way for me to get all defined constant for a given namespace? That way, I could construct a function to get all defined constants and write something more elegant like in_array($service, getConstants($this->getNamespace()), true).

Can you give me a hint?

Upvotes: 3

Views: 1785

Answers (1)

Michael
Michael

Reputation: 12806

You can get all user defined constants with get_defined_constants and then check the namespace using strpos:

$constants = get_defined_constants(TRUE)['user'];

foreach ($constants as $name => $value)
{

  if (0 === strpos($name, 'services\storage\connectors'))
  {
    $services_storage_connectors[] = $name;
  }

}

echo '<pre>' . print_r($services_storage_connectors, TRUE) . '</pre>';

/*

Array
(
    [0] => services\storage\connectors\Box
    [1] => services\storage\connectors\Dropbox
    [2] => services\storage\connectors\FTP
    [3] => services\storage\connectors\GoogleDrive
    [4] => services\storage\connectors\Local
)

*/

Note that $name is lowercase, even if the namespace is defined with uppercase letters.

Edit: In case you'd like it in fewer lines

  $constants = array_filter(array_keys(get_defined_constants(TRUE)['user']), function ($name)
  {
    return 0 === strpos($name, 'services\storage\connectors');
  }
  );

Upvotes: 3

Related Questions