public function listen()
    {
        $this->Discord->on('ready', function ($discord) {
            $discord->on('message', function ($message) {
                if ($this->Discord->id === $message->author->id) {
                    return;
                }

                $content = Message::parse($message->content);
                $wrapper = Wrapper::getInstance()->setInstances($message, $this->ModuleManager);

                //Handle the type of the message.
                //Note : The order is very important !
                if ($wrapper->Channel->is_private === true) {
                    $this->ModuleManager->onPrivateMessage($wrapper, $content);
                } elseif ($content['commandCode'] === Configure::read('Command.prefix') &&
                            isset(Configure::read('Commands')[$content['command']])) {
                    $command = Configure::read('Commands')[$content['command']];

                    if ((isset($command['admin']) && $command['admin'] === true) &&
                            !User::hasPermission($wrapper->Message->author->id, Configure::read('Bot.admins'))) {
                        $wrapper->Message->reply('You are not administrator of the bot.');

                        return;
                    }

                    if (count($content['arguments']) < $command['params']) {
                        $wrapper->Message->reply(Command::syntax($content));

                        return;
                    }

                    $this->ModuleManager->onCommandMessage($wrapper, $content);
                } else {
                    $this->ModuleManager->onChannelMessage($wrapper, $content);
                }
            });
        });
    }

public
function
listen
(
)
{
$
this
->
Discord
->
on
(
'ready'
,
function
(
$
discord
)
{
$
discord
->
on
(
'message'
,
function
(
$
message
)
{
if
(
$
this
->
Discord
->
id
===
$
message
->
author
->
id
)
{
return
;
}
$
content
=
Message
::
parse
(
$
message
->
content
)
;
$
wrapper
=
Wrapper
::
getInstance
(
)
->
setInstances
(
$
message
,
$
this
->
ModuleManager
)
;
//Handle the type of the message.
//Note : The order is very important !
if
(
$
wrapper
->
Channel
->
is_private
===
true
)
{
$
this
->
ModuleManager
->
onPrivateMessage
(
$
wrapper
,
$
content
)
;
}
elseif
(
$
content
[
'commandCode'
]
===
Configure
::
read
(
'Command.prefix'
)
&&
isset
(
Configure
::
read
(
'Commands'
)
[
$
content
[
'command'
]
]
)
)
{
$
command
=
Configure
::
read
(
'Commands'
)
[
$
content
[
'command'
]
]
;
if
(
(
isset
(
$
command
[
'admin'
]
)
&&
$
command
[
'admin'
]
===
true
)
&&
!
User
::
hasPermission
(
$
wrapper
->
Message
->
author
->
id
,
Configure
::
read
(
'Bot.admins'
)
)
)
{
$
wrapper
->
Message
->
reply
(
'You are not administrator of the bot.'
)
;
return
;
}
if
(
count
(
$
content
[
'arguments'
]
)
<
$
command
[
'params'
]
)
{
$
wrapper
->
Message
->
reply
(
Command
::
syntax
(
$
content
)
)
;
return
;
}
$
this
->
ModuleManager
->
onCommandMessage
(
$
wrapper
,
$
content
)
;
}
else
{
$
this
->
ModuleManager
->
onChannelMessage
(
$
wrapper
,
$
content
)
;
}
}
)
;
}
)
;
}


public static function parse($message)
    {
        static::resetConfig();

        $chr32 = chr(32);
        $config = [];

        if (empty($message) || !is_string($message)) {
            return static::read();
        }

        $config += [
            'raw' => $message,
            'parts' => explode($chr32, trim($message), 2)
        ];

        $config += [
            'commandCode' => substr($config['parts'][0], 0, 1),
            'command' => strtolower(substr($config['parts'][0], 1))
        ];

        if (count($config['parts']) > 1) {
            $config += [
                'message' => $config['parts'][1],
                'arguments' => array_map(
                    'strtolower',
                    explode(
                        $chr32,
                        $config['parts'][1]
                    )
                )
            ];
        }
        static::config($config);

        return static::read();
    }

public static function parse ( $ message ) { static :: resetConfig ( ) ; $ chr32 = chr ( 32 ) ; $ config = [ ] ; if ( empty ( $ message ) || ! is_string ( $ message ) ) { return static :: read ( ) ; } $ config += [ 'raw' => $ message , 'parts' => explode ( $ chr32 , trim ( $ message ) , 2 ) ] ; $ config += [ 'commandCode' => substr ( $ config [ 'parts' ] [ 0 ] , 0 , 1 ) , 'command' => strtolower ( substr ( $ config [ 'parts' ] [ 0 ] , 1 ) ) ] ; if ( count ( $ config [ 'parts' ] ) > 1 ) { $ config += [ 'message' => $ config [ 'parts' ] [ 1 ] , 'arguments' => array_map ( 'strtolower' , explode ( $ chr32 , $ config [ 'parts' ] [ 1 ] ) ) ] ; } static :: config ( $ config ) ; return static :: read ( ) ; }

Parse the message and return an array with informations about the message.

### Usage
```
Message::parse('!say hi');
```
Wil return this array:
```
[
'raw' => '!say hi',
'parts' => [
(int) 0 => '!say',
(int) 1 => 'hi'
],
'command' => 'say',
'message' => 'hi',
'commandCode' => '!',
'arguments' => [
(int) 0 => 'hi'
]
]

```

@param string $message The message to parse.

@return array The data.

Parse the message and return an array with informations about the message .


protected function getFilePath($key, $checkExists = false)
    {
        if (strpos($key, '..') !== false) {
            throw new Exception('Cannot load/dump configuration files with ../ in them.');
        }

        list($plugin, $key) = pluginSplit($key);

        if ($plugin) {
            $file = Plugin::configPath($plugin) . $key;
        } else {
            $file = $this->path . $key;
        }

        $file .= $this->extension;

        if (!$checkExists || is_file($file)) {
            return $file;
        }

        if (is_file(realpath($file))) {
            return realpath($file);
        }

        throw new Exception(sprintf('Could not load configuration file: %s', $file));
    }

Get file path

@param string $key The identifier to write to. If the key has a . it will be treated
as a plugin prefix.
@param bool $checkExists Whether to check if file exists. Defaults to false.

@return string Full file path

@throws \Skinny\Core\Exception\Exception When files don't exist or when
files contain '..' as this could lead to abusive reads.


public static function load($plugin, array $config = [])
    {
        if (is_array($plugin)) {
            foreach ($plugin as $name => $conf) {
                list($name, $conf) = (is_numeric($name)) ? [$conf, $config] : [$name, $conf];
                static::load($name, $conf);
            }

            return;
        }

        static::loadConfig();

        $config += [
            'bootstrap' => false,
            'classBase' => 'src',
            'ignoreMissing' => false
        ];

        if (!isset($config['path'])) {
            $config['path'] = Configure::read('plugins.' . $plugin);
        }

        if (empty($config['path'])) {
            $paths = (array)Configure::read('App.paths.plugins');
            $pluginPath = str_replace('/', DIRECTORY_SEPARATOR, $plugin);
            foreach ($paths as $path) {
                if (is_dir($path . $pluginPath)) {
                    $config['path'] = $path . $pluginPath . DIRECTORY_SEPARATOR;
                    break;
                }
            }
        }

        if (empty($config['path'])) {
            throw new MissingPluginException(['plugin' => $plugin]);
        }

        $config['classPath'] = $config['path'] . $config['classBase'] . DIRECTORY_SEPARATOR;
        if (!isset($config['configPath'])) {
            $config['configPath'] = $config['path'] . 'config' . DIRECTORY_SEPARATOR;
        }

        static::$plugins[$plugin] = $config;

        if ($config['bootstrap'] === true) {
            static::bootstrap($plugin);
        }
    }

public static function load ( $ plugin , array $ config = [ ] ) { if ( is_array ( $ plugin ) ) { foreach ( $ plugin as $ name => $ conf ) { list ( $ name , $ conf ) = ( is_numeric ( $ name ) ) ? [ $ conf , $ config ] : [ $ name , $ conf ] ; static :: load ( $ name , $ conf ) ; } return ; } static :: loadConfig ( ) ; $ config += [ 'bootstrap' => false , 'classBase' => 'src' , 'ignoreMissing' => false ] ; if ( ! isset ( $ config [ 'path' ] ) ) { $ config [ 'path' ] = Configure :: read ( 'plugins.' . $ plugin ) ; } if ( empty ( $ config [ 'path' ] ) ) { $ paths = ( array ) Configure :: read ( 'App.paths.plugins' ) ; $ pluginPath = str_replace ( '/' , DIRECTORY_SEPARATOR , $ plugin ) ; foreach ( $ paths as $ path ) { if ( is_dir ( $ path . $ pluginPath ) ) { $ config [ 'path' ] = $ path . $ pluginPath . DIRECTORY_SEPARATOR ; break ; } } } if ( empty ( $ config [ 'path' ] ) ) { throw new MissingPluginException ( [ 'plugin' => $ plugin ] ) ; } $ config [ 'classPath' ] = $ config [ 'path' ] . $ config [ 'classBase' ] . DIRECTORY_SEPARATOR ; if ( ! isset ( $ config [ 'configPath' ] ) ) { $ config [ 'configPath' ] = $ config [ 'path' ] . 'config' . DIRECTORY_SEPARATOR ; } static :: $ plugins [ $ plugin ] = $ config ; if ( $ config [ 'bootstrap' ] === true ) { static :: bootstrap ( $ plugin ) ; } }

Loads a plugin and optionally loads bootstrap files.

### Examples:

`Plugin::load('Basic')`

Will load the Basic plugin and will not load the bootstrap file.

`Plugin::load('Basic', ['bootstrap' => true])`

Will load the bootstrap.php file.

It is also possible to load multiple plugins at once. Examples:

`Plugin::load(['Basic', 'Developer'])`

Will load the Basic and Developer plugins.

`Plugin::load(['Basic', 'Developer'], ['bootstrap' => true])`

Will load bootstrap file for both plugins

### Configuration options

- `bootstrap` - array - Whether or not you want the $plugin/config/bootstrap.php file loaded.
- `ignoreMissing` - boolean - Set to true to ignore missing bootstrap files.
- `path` - string - The path the plugin can be found on. If empty the default plugin path will be used.
- `classBase` - string - The path relative to `path` which contains the folders with class files.
Defaults to "src".

@param string|array $plugin Name of the plugin to be loaded in CamelCase format or array or plugins to load.
@param array $config Configuration options for the plugin.

@throws \Skinny\Core\Exception\MissingPluginException If the folder for the plugin to be loaded is not found.

@return void

Loads a plugin and optionally loads bootstrap files .


protected static function loadConfig()
    {
        if (Configure::check('plugins')) {
            return;
        }
        $vendorFile = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'skinny-plugins.php';
        if (!file_exists($vendorFile)) {
            $vendorFile = dirname(dirname(dirname(dirname(__DIR__)))) . DIRECTORY_SEPARATOR . 'skinny-plugins.php';
            if (!file_exists($vendorFile)) {
                Configure::write(['plugins' => []]);

                return;
            }
        }

        $config = require $vendorFile;
        Configure::write($config);
    }

protected static function loadConfig ( ) { if ( Configure :: check ( 'plugins' ) ) { return ; } $ vendorFile = dirname ( dirname ( __DIR__ ) ) . DIRECTORY_SEPARATOR . 'skinny-plugins.php' ; if ( ! file_exists ( $ vendorFile ) ) { $ vendorFile = dirname ( dirname ( dirname ( dirname ( __DIR__ ) ) ) ) . DIRECTORY_SEPARATOR . 'skinny-plugins.php' ; if ( ! file_exists ( $ vendorFile ) ) { Configure :: write ( [ 'plugins' => [ ] ] ) ; return ; } } $ config = require $ vendorFile ; Configure :: write ( $ config ) ; }

Load the plugin path configuration file.

@return void

Load the plugin path configuration file .


public static function loadAll(array $options = [])
    {
        static::loadConfig();
        $plugins = [];
        foreach ((array)Configure::read('App.paths.plugins') as $path) {
            if (!is_dir($path)) {
                continue;
            }
            $dir = new DirectoryIterator($path);
            foreach ($dir as $path) {
                if ($path->isDir() && !$path->isDot()) {
                    $plugins[] = $path->getBasename();
                }
            }
        }
        if (Configure::check('plugins')) {
            $plugins = array_merge($plugins, array_keys(Configure::read('plugins')));
            $plugins = array_unique($plugins);
        }

        foreach ($plugins as $p) {
            $opts = isset($options[$p]) ? $options[$p] : null;
            if ($opts === null && isset($options[0])) {
                $opts = $options[0];
            }
            if (isset(static::$plugins[$p])) {
                continue;
            }
            static::load($p, (array)$opts);
        }
    }

public static function loadAll ( array $ options = [ ] ) { static :: loadConfig ( ) ; $ plugins = [ ] ; foreach ( ( array ) Configure :: read ( 'App.paths.plugins' ) as $ path ) { if ( ! is_dir ( $ path ) ) { continue ; } $ dir = new DirectoryIterator ( $ path ) ; foreach ( $ dir as $ path ) { if ( $ path -> isDir ( ) && ! $ path -> isDot ( ) ) { $ plugins [ ] = $ path -> getBasename ( ) ; } } } if ( Configure :: check ( 'plugins' ) ) { $ plugins = array_merge ( $ plugins , array_keys ( Configure :: read ( 'plugins' ) ) ) ; $ plugins = array_unique ( $ plugins ) ; } foreach ( $ plugins as $ p ) { $ opts = isset ( $ options [ $ p ] ) ? $ options [ $ p ] : null ; if ( $ opts === null && isset ( $ options [ 0 ] ) ) { $ opts = $ options [ 0 ] ; } if ( isset ( static :: $ plugins [ $ p ] ) ) { continue ; } static :: load ( $ p , ( array ) $ opts ) ; } }

Will load all the plugins located in the default plugin folder.

If passed an options array, it will be used as a common default for all plugins to be loaded
It is possible to set specific defaults for each plugins in the options array. Examples:

```
Plugin::loadAll([
['bootstrap' => true],
'Basic' => ['bootstrap' => false],
]);
```

The above example will load the bootstrap file for all plugins,
but for Basic it will not load the bootstrap file.

If a plugin has been loaded already, it will not be reloaded by loadAll().

@param array $options Options.

@return void

Will load all the plugins located in the default plugin folder .


public static function bootstrap($plugin)
    {
        $config = static::$plugins[$plugin];
        if ($config['bootstrap'] === false) {
            return false;
        }
        if ($config['bootstrap'] === true) {
            return static::includeFile(
                $config['configPath'] . 'bootstrap.php',
                $config['ignoreMissing']
            );
        }
    }

public static function bootstrap ( $ plugin ) { $ config = static :: $ plugins [ $ plugin ] ; if ( $ config [ 'bootstrap' ] === false ) { return false ; } if ( $ config [ 'bootstrap' ] === true ) { return static :: includeFile ( $ config [ 'configPath' ] . 'bootstrap.php' , $ config [ 'ignoreMissing' ] ) ; } }

Loads the bootstrapping files for a plugin, or calls the initialization setup in the configuration.

@param string $plugin Name of the plugin.

@return mixed

@see \Skinny\Core\Plugin::load() for examples of bootstrap configuration

Loads the bootstrapping files for a plugin or calls the initialization setup in the configuration .


public function read($key)
    {
        $file = $this->getFilePath($key, true);

        $return = include $file;
        if (!is_array($return)) {
            throw new Exception(sprintf('Config file "%s" did not return an array', $key . '.php'));
        }

        return $return;
    }

Read a config file and return its contents.

Files with `.` in the name will be treated as values in plugins. Instead of
reading from the initialized path, plugin keys will be located using Plugin::path().

@param string $key The identifier to read from. If the key has a . it will be treated
as a plugin prefix.

@return array Parsed configuration values.

@throws \Skinny\Core\Exception\Exception when files don't exist or they don't contain `$config`.
Or when files contain '..' as this could lead to abusive reads.

Read a config file and return its contents .


public static function config($key, $value = null)
    {
        if (is_string($key)) {
            static::$config[$key] = $value;

            return;
        }

        if (!is_array($key)) {
            throw new InvalidArgumentException('Only string and array can be passed to config.');
        }

        foreach ($key as $name => $value) {
            static::$config[$name] = $value;
        }

        return;
    }

This method can be used to define configuration.

### Usage

Writing config data:

```
Message::config('message', 'hi');
```

Writing multiple config data at once:

```
Message::config(['message' => 'hi', 'commandCode' => '!']);
```

@param string|array $key The name of the configuration to read, or an array of multiple configs.

@return null

@throws \InvalidArgumentException If the key is not a string or an array.

This method can be used to define configuration .


public static function read($key = null)
    {
        if ($key === null) {
            return static::$config;
        }

        return isset(static::$config[$key]) ? static::$config[$key] : null;
    }

public static function read ( $ key = null ) { if ( $ key === null ) { return static :: $ config ; } return isset ( static :: $ config [ $ key ] ) ? static :: $ config [ $ key ] : null ; }

Read a config variable or all the config.

### Usage

Reading config with key:

```
Message::read('message');
```

Reading all the config:

```
Message::read();
```

@param string|null The key to read the configuration.

@return mixed

Read a config variable or all the config .


protected function loadModules(DirectoryIterator $files, array $config = [])
    {
        foreach ($files as $file) {
            $filename = $file->getFilename();
            if ($file->isDot() || $file->isDir() || $filename[0] == '.') {
                continue;
            } elseif ($file->isFile() && substr($filename, -4) != '.php') {
                continue;
            } else {
                try {
                    $this->load(substr($filename, 0, -4), $config);
                } catch (Exception $e) {
                    throw new RuntimeException(sprintf('Error while loading module : %s', $e->getMessage()));
                }
            }
        }
    }

protected
function
loadModules
(
DirectoryIterator
$
files
,
array
$
config
=
[
]
)
{
foreach
(
$
files
as
$
file
)
{
$
filename
=
$
file
->
getFilename
(
)
;
if
(
$
file
->
isDot
(
)
||
$
file
->
isDir
(
)
||
$
filename
[
0
]
==
'.'
)
{
continue
;
}
elseif
(
$
file
->
isFile
(
)
&&
substr
(
$
filename
,
4
)
!=
'.php'
)
{
continue
;
}
else
{
try
{
$
this
->
load
(
substr
(
$
filename
,
0
,
4
)
,
$
config
)
;
}
catch
(
Exception
$
e
)
{
throw
new
RuntimeException
(
sprintf
(
'Error while loading module : %s'
,
$
e
->
getMessage
(
)
)
)
;
}
}
}
}

Loads the list of modules in the DirectoryIterator.

Options :
- pathDir : The full path of the Modules directory. Default to MODULE_DIR.
- plugin : The plugin name or false if no plugin. Default to false.

@param \DirectoryIterator $files The DirectoryIterator instance.
@param array $config The configuration options.

@throws \RuntimeException When the class doesn't implement the ModuleInterface.

@return string

Loads the list of modules in the DirectoryIterator .


protected function checkPlugins($module)
    {
        $loadedPlugins = Configure::read('plugins');
        $arr = [];

        if (empty($loadedPlugins) || !is_array($loadedPlugins)) {
            return $arr;
        }

        foreach ($loadedPlugins as $plugin => $pluginPath) {
            $pluginPath = Plugin::classPath($plugin) . 'Module' . DS . 'Modules';
            $files = new DirectoryIterator($pluginPath);

            foreach ($files as $file) {
                $filename = $file->getFilename();

                if ($file->isDot() || $file->isDir() || $filename[0] == '.') {
                    continue;
                } elseif ($file->isFile() && substr($filename, -4) != '.php') {
                    continue;
                } elseif (Inflector::camelize(substr($filename, 0, -4)) !== $module) {
                    continue;
                } else {
                    $arr = ['pathDir' => $pluginPath, 'plugin' => $plugin];

                    return $arr;
                }
            }
        }

        return $arr;
    }

protected function checkPlugins ( $ module ) { $ loadedPlugins = Configure :: read ( 'plugins' ) ; $ arr = [ ] ; if ( empty ( $ loadedPlugins ) || ! is_array ( $ loadedPlugins ) ) { return $ arr ; } foreach ( $ loadedPlugins as $ plugin => $ pluginPath ) { $ pluginPath = Plugin :: classPath ( $ plugin ) . 'Module' . DS . 'Modules' ; $ files = new DirectoryIterator ( $ pluginPath ) ; foreach ( $ files as $ file ) { $ filename = $ file -> getFilename ( ) ; if ( $ file -> isDot ( ) || $ file -> isDir ( ) || $ filename [ 0 ] == '.' ) { continue ; } elseif ( $ file -> isFile ( ) && substr ( $ filename , - 4 ) != '.php' ) { continue ; } elseif ( Inflector :: camelize ( substr ( $ filename , 0 , - 4 ) ) !== $ module ) { continue ; } else { $ arr = [ 'pathDir' => $ pluginPath , 'plugin' => $ plugin ] ; return $ arr ; } } } return $ arr ; }

Check if the module exist in the plugin list. Primary used when we need to load a module and
the module doesn't exists in the application itself.

@param string $module The module to check.

@return array The config needed for the ModuleManager::load() function.

Check if the module exist in the plugin list . Primary used when we need to load a module and the module doesn t exists in the application itself .


public function unload($module)
    {
        $module = Inflector::camelize($module);

        if (!isset($this->loadedModules[$module])) {
            //Return the message AlreadyUnloaded.
            return 'AU';
        }

        //Remove this module, also calling the __destruct method of it.
        $object = $this->loadedModules[$module]['object'];
        unset($object);
        unset($this->loadedModules[$module]);

        //Return the message Unloaded.
        return 'U';
    }

Unload a module from the Framework.

@param string $module Module to unload.

@return string


public function reload($module)
    {
        $module = Inflector::camelize($module);
        $config = [];

        if (isset($this->loadedModules[$module]) && $this->loadedModules[$module]['plugin'] === true) {
            $config += [
                'pathDir' => $this->loadedModules[$module]['pluginPath'],
                'plugin' => $this->loadedModules[$module]['pluginName']
            ];
        }

        $unload = $this->unload($module);

        if ($unload != "U") {
            return $unload;
        }

        return $this->load($module, $config);
    }

public function reload ( $ module ) { $ module = Inflector :: camelize ( $ module ) ; $ config = [ ] ; if ( isset ( $ this -> loadedModules [ $ module ] ) && $ this -> loadedModules [ $ module ] [ 'plugin' ] === true ) { $ config += [ 'pathDir' => $ this -> loadedModules [ $ module ] [ 'pluginPath' ] , 'plugin' => $ this -> loadedModules [ $ module ] [ 'pluginName' ] ] ; } $ unload = $ this -> unload ( $ module ) ; if ( $ unload != "U" ) { return $ unload ; } return $ this -> load ( $ module , $ config ) ; }

Reloads a module by first calling unload and then load.

@param string $module The module to reload.

@return string

Reloads a module by first calling unload and then load .


public function timeLoaded($module)
    {
        $module = Inflector::camelize($module);

        if (!isset($this->loadedModules[$module])) {
            return false;
        }

        return $this->loadedModules[$module]['loaded'];
    }

public function timeLoaded ( $ module ) { $ module = Inflector :: camelize ( $ module ) ; if ( ! isset ( $ this -> loadedModules [ $ module ] ) ) { return false ; } return $ this -> loadedModules [ $ module ] [ 'loaded' ] ; }

Returns the time when a module was loaded or false if we don't have it.

@param string $module The module to check the time.

@return false|int

Returns the time when a module was loaded or false if we don t have it .


public function isModified($module)
    {
        $module = Inflector::camelize($module);

        if (!isset($this->loadedModules[$module])) {
            return -1;
        }

        return $this->loadedModules[$module]['modified'];
    }

public function isModified ( $ module ) { $ module = Inflector :: camelize ( $ module ) ; if ( ! isset ( $ this -> loadedModules [ $ module ] ) ) { return - 1 ; } return $ this -> loadedModules [ $ module ] [ 'modified' ] ; }

Returns if a module has been modified or -1 if we do not have it

@param string $module The module to check.

@return bool|int

Returns if a module has been modified or - 1 if we do not have it


public function offsetGet($module)
    {
        $module = Inflector::camelize($module);

        if (!isset($this->loadedModules[$module])) {
            return false;
        }

        return $this->loadedModules[$module];
    }

public function offsetGet ( $ module ) { $ module = Inflector :: camelize ( $ module ) ; if ( ! isset ( $ this -> loadedModules [ $ module ] ) ) { return false ; } return $ this -> loadedModules [ $ module ] ; }

Returns the module if we have it, or false if we don't have it.

@param string $module The module to get.

@return bool|object

Returns the module if we have it or false if we don t have it .


public function offsetExists($module)
    {
        $module = Inflector::camelize($module);

        return isset($this->loadedModules[$module]);
    }

public function offsetExists ( $ module ) { $ module = Inflector :: camelize ( $ module ) ; return isset ( $ this -> loadedModules [ $ module ] ) ; }

Check if we have loaded a certain module.

@param string $module The module to check.

@return bool

Check if we have loaded a certain module .


public function offsetSet($offset, $module)
    {
        if (!$module instanceof ModuleInterface) {
            throw new RuntimeException(
                sprintf('ModuleManager::offsetSet() expects "%s" to be an instance of ModuleInterface.', $module)
            );
        }

        $newModule = [
            'object' => $module,
            'loaded' => time(),
            'plugin' => false,
            'pluginName' => '',
            'pluginPath' => MODULE_DIR,
            'name' => get_class($module),
            'modified' => false
        ];

        if (in_array($offset, $this->priorityList)) {
            $temp = array_reverse($this->loadedModules, true);
            $temp[$offset] = $newModule;
            $this->loadedModules = array_reverse($temp, true);
        } else {
            $this->loadedModules[$offset] = $newModule;
        }
    }

Creates a new Module in our list.

@param string $offset The offset of the moddule.
@param object $module The module to create.

@throws \RuntimeException

@return void


public function get($key, $default = null)
    {
        $result = $this->call('get', [$key]);
        if ($result === false || $result === null) {
            return $default;
        }

        return $result;
    }

public function get ( $ key , $ default = null ) { $ result = $ this -> call ( 'get' , [ $ key ] ) ; if ( $ result === false || $ result === null ) { return $ default ; } return $ result ; }

Get the value related to the specified key

@param string $key
@param mixed  $default

@return string|bool


public function set($key, $value, $ttl = null): bool
    {
        $ttl    = $this->getTtl($ttl);
        $params = ($ttl <= 0) ? [$key, $value] : [$key, $value, $ttl];

        return $this->call('set', $params);
    }

public function set ( $ key , $ value , $ ttl = null ) : bool { $ ttl = $ this -> getTtl ( $ ttl ) ; $ params = ( $ ttl <= 0 ) ? [ $ key , $ value ] : [ $ key , $ value , $ ttl ] ; return $ this -> call ( 'set' , $ params ) ; }

Set the string value in argument as value of the key.

@param string $key
@param mixed  $value
@param int    $ttl unit is seconds

@return bool

Set the string value in argument as value of the key .


public function getMultiple($keys, $default = null)
    {
        $mgetResult = $this->call('mget', [$keys]);
        if ($mgetResult === false) {
            return $default;
        }
        $result = [];
        foreach ($mgetResult ?? [] as $key => $value) {
            $result[$keys[$key]] = $value;
        }

        return $result;
    }

public function getMultiple ( $ keys , $ default = null ) { $ mgetResult = $ this -> call ( 'mget' , [ $ keys ] ) ; if ( $ mgetResult === false ) { return $ default ; } $ result = [ ] ; foreach ( $ mgetResult ?? [ ] as $ key => $ value ) { $ result [ $ keys [ $ key ] ] = $ value ; } return $ result ; }

Returns the values of all specified keys.
For every key that does not hold a string value or does not exist,
the special value false is returned. Because of this, the operation never fails.

@param iterable $keys
@param mixed    $default

@return array|mixed

Returns the values of all specified keys . For every key that does not hold a string value or does not exist the special value false is returned . Because of this the operation never fails .


public function setMultiple($values, $ttl = null): bool
    {
        $result = $this->call('mset', [$values]);

        return $result;
    }

public function setMultiple ( $ values , $ ttl = null ) : bool { $ result = $ this -> call ( 'mset' , [ $ values ] ) ; return $ result ; }

Sets multiple key-value pairs in one atomic command.

@param iterable $values
@param int      $ttl

@return bool TRUE in case of success, FALSE in case of failure.

Sets multiple key - value pairs in one atomic command .


public function call(string $method, array $params)
    {
        /* @var PoolInterface $connectPool */
        $connectPool = App::getPool($this->poolName);
        /* @var ConnectionInterface $client */
        $connection = $connectPool->getConnection();
        $result     = $connection->$method(...$params);
        $connection->release(true);

        return $result;
    }

public
function
call
(
string
$
method
,
array
$
params
)
{
/* @var PoolInterface $connectPool */
$
connectPool
=
App
::
getPool
(
$
this
->
poolName
)
;
/* @var ConnectionInterface $client */
$
connection
=
$
connectPool
->
getConnection
(
)
;
$
result
=
$
connection
->
$
method
(
...
$
params
)
;
$
connection
->
release
(
true
)
;
return
$
result
;
}

call method by redis client

@param string $method
@param array  $params

@return mixed


public function before(JoinPoint $joinPoint)
    {
        $profileKey = $this->getProfileKey($joinPoint);
        Log::profileStart($profileKey);
    }

public function before ( JoinPoint $ joinPoint ) { $ profileKey = $ this -> getProfileKey ( $ joinPoint ) ; Log :: profileStart ( $ profileKey ) ; }

before of method

@Before()
@param JoinPoint $joinPoint


public function afterReturning(JoinPoint $joinPoint)
    {
        $profileKey = $this->getProfileKey($joinPoint);
        Log::profileEnd($profileKey);

        return $joinPoint->getReturn();
    }

public function afterReturning ( JoinPoint $ joinPoint ) { $ profileKey = $ this -> getProfileKey ( $ joinPoint ) ; Log :: profileEnd ( $ profileKey ) ; return $ joinPoint -> getReturn ( ) ; }

afterReturning of method

@AfterReturning()
@param JoinPoint $joinPoint

@return mixed


private function getProfileKey(JoinPoint $joinPoint)
    {
        $method = $joinPoint->getMethod();
        if ($method == '__call') {
            list($method) = $joinPoint->getArgs();
        }

        return self::PROFILE_PREFIX . '.' . $method;
    }

private function getProfileKey ( JoinPoint $ joinPoint ) { $ method = $ joinPoint -> getMethod ( ) ; if ( $ method == '__call' ) { list ( $ method ) = $ joinPoint -> getArgs ( ) ; } return self :: PROFILE_PREFIX . '.' . $ method ; }

the key of profile

@param JoinPoint $joinPoint

@return string


public static function all(CommandInterface $command, $prefix)
    {
        if ($arguments = $command->getArguments()) {
            foreach ($arguments as &$key) {
                $key = "$prefix$key";
            }
            $arguments = [$arguments];

            $command->setRawArguments($arguments);
        }
    }

public static function all ( CommandInterface $ command , $ prefix ) { if ( $ arguments = $ command -> getArguments ( ) ) { foreach ( $ arguments as & $ key ) { $ key = "$prefix$key" ; } $ arguments = [ $ arguments ] ; $ command -> setRawArguments ( $ arguments ) ; } }

Applies the specified prefix to all the arguments.

@param CommandInterface $command Command instance.
@param string           $prefix  Prefix string.

Applies the specified prefix to all the arguments .


public static function interleaved(CommandInterface $command, $prefix)
    {
        if ($arguments = $command->getArguments()) {
            $newArguments = [];
            foreach ($arguments as $key => $value) {
                $newKey = "{$prefix}{$key}";
                $newArguments[$newKey] = $value;
            }
            $arguments = [$newArguments];

            $command->setRawArguments($arguments);
        }
    }

public static function interleaved ( CommandInterface $ command , $ prefix ) { if ( $ arguments = $ command -> getArguments ( ) ) { $ newArguments = [ ] ; foreach ( $ arguments as $ key => $ value ) { $ newKey = "{$prefix}{$key}" ; $ newArguments [ $ newKey ] = $ value ; } $ arguments = [ $ newArguments ] ; $ command -> setRawArguments ( $ arguments ) ; } }

Applies the specified prefix only to even arguments in the list.

@param CommandInterface $command Command instance.
@param string           $prefix  Prefix string.

Applies the specified prefix only to even arguments in the list .


public static function evalKeys(CommandInterface $command, $prefix)
    {
        if ($arguments = $command->getArguments()) {
            $command->setRawArguments($arguments);
        }
    }

public static function evalKeys ( CommandInterface $ command , $ prefix ) { if ( $ arguments = $ command -> getArguments ( ) ) { $ command -> setRawArguments ( $ arguments ) ; } }

Applies the specified prefix to the keys of an EVAL-based command.

@param CommandInterface $command Command instance.
@param string           $prefix  Prefix string.

Applies the specified prefix to the keys of an EVAL - based command .


protected function setExpires()
    {
        $created = $this->created;

        if ($this->lifetime === null) {
            $this->lifetime = self::DEFAULT_LIFETIME;
        }

        $this->expires = $created->modify($this->lifetime);
    }

protected function setExpires ( ) { $ created = $ this -> created ; if ( $ this -> lifetime === null ) { $ this -> lifetime = self :: DEFAULT_LIFETIME ; } $ this -> expires = $ created -> modify ( $ this -> lifetime ) ; }

Set the 'expires' property by adding lifetime to the 'created'  property.

@return void

Set the expires property by adding lifetime to the created property .


protected function setLength($length)
    {
        if ($length === null) {
            $length = self::DEFAULT_LENGTH;
        }

        $this->length = $length;
    }

protected function setLength ( $ length ) { if ( $ length === null ) { $ length = self :: DEFAULT_LENGTH ; } $ this -> length = $ length ; }

Sets the length of generated token.

@param int $length Token length
@throws \InvalidArgumentException
@return void


public function read($length = null)
    {
        $data = fread($this->socket, $length === null ? $this->bufferLen : $length);
        if ($this->debug) {
            OrientDBHelpers::hexDump($data);
        }
        return $data;
    }

public function read ( $ length = null ) { $ data = fread ( $ this -> socket , $ length === null ? $ this -> bufferLen : $ length ) ; if ( $ this -> debug ) { OrientDBHelpers :: hexDump ( $ data ) ; } return $ data ; }

Read bytes from socket
@param int $length Bytes to read
@return string


public function send($data)
    {
        fwrite($this->socket, $data);
        if ($this->debug) {
            OrientDBHelpers::hexDump($data);
        }
    }

public function send ( $ data ) { fwrite ( $ this -> socket , $ data ) ; if ( $ this -> debug ) { OrientDBHelpers :: hexDump ( $ data ) ; } }


protected function canExecute($command)
    {

        if (!$this->active) {
            throw new OrientDBWrongCommandException('DBClose was executed. No interaction is possible.');
        }
        if (in_array($command->opType, $this->getCommandsRequiresConnect()) && !$this->isConnected()) {
            throw new OrientDBWrongCommandException('Not connected to server');
        }
        if (in_array($command->opType, $this->getCommandsRequiresDBOpen()) && !$this->isDBOpen()) {
            throw new OrientDBWrongCommandException('Database not open');
        }
    }

Check if command's requirements are met
@param OrientDBCommandAbstract $command Command instance
@throws OrientDBWrongCommandException
@see OrientDBCommandAbstract


public function setProtocolVersion($version)
    {
        $this->protocolVersion = $version;
        if ($this->protocolVersion < $this->clientVersion) {
            throw new OrientDBException('Binary protocol is uncompatible with the Server connected: clientVersion=' . $this->clientVersion . ', serverVersion=' . $this->protocolVersion);
        }
    }

Check if current client protocol version matches server version
@param int $version Server version
@throws OrientDBException


protected function process($data, $isAssoc = true, $isArray = false)
    {
        $tokens = array();

        foreach ($data as $key => $value) {
            $buffer = '';
            if ($isAssoc) {
                if ($isArray) {
                    $buffer = self::encodeString($key) . ':';
                } else {
                    $buffer = $key . ':';
                }
            }
            /**
             *
             * PHP manual says what gettype() is slow and we should use is_* functions instead. But tests says that its approx. 5-10% faster encoding using single gettype() call instead of separate calls to is_int(), is_string(), etc.
             * @var string
             */
            $valueType = gettype($value);
            switch ($valueType) {
                case 'integer':
                    $buffer .= $value;
                    break;

                case 'double':
                    $buffer .= $value . chr(OrientDBRecordDecoder::CCODE_NUM_FLOAT);
                    break;

                case 'string':
                    $buffer .= self::encodeString($value);
                    break;

                case 'boolean':
                    if ($value === true) {
                        $buffer .= 'true';
                    } else {
                        $buffer .= 'false';
                    }
                    break;

                case 'array':
                    $arrayAssoc = self::isAssoc($value);
                    if ($arrayAssoc === true) {
//                        This is assoc array, using map
                        $boundStart = chr(OrientDBRecordDecoder::CCODE_OPEN_CURLY);
                        $boundEnd = chr(OrientDBRecordDecoder::CCODE_CLOSE_CURLY);
                    } else {
//                        Array will always be encoded as a set, as 1) Orient itself converts set to list (and vice-versa too) 2) PHP lacks build-in set type
                        $boundStart = chr(OrientDBRecordDecoder::CCODE_OPEN_SQUARE);
                        $boundEnd = chr(OrientDBRecordDecoder::CCODE_CLOSE_SQUARE);
                    }
                    $buffer .= $boundStart;
                    /**
                     * @TODO Fix possible PHP fatal: Maximum function nesting level of '100' reached, aborting!
                     */
                    $buffer .= implode(',', $this->process($value, $arrayAssoc, true));
                    $buffer .= $boundEnd;
                    break;

                case 'NULL':

                    break;

                case is_a($value, 'OrientDBTypeLink'):
                    /** @var $value OrientDBTypeLink */
                    $buffer .= $value->getHash();
                    break;

                case is_a($value, 'OrientDBTypeDate'):
                    $buffer .= (string) $value;
                    break;

                case is_a($value, 'OrientDBRecord'):
                    $buffer .= chr(OrientDBRecordDecoder::CCODE_OPEN_PARENTHESES);
                    /** @var $value OrientDBRecord */
                    $buffer .= $value->__toString();
                    $buffer .= chr(OrientDBRecordDecoder::CCODE_CLOSE_PARENTHESES);
                    break;

                default:
                    throw new OrientDBException('Can\'t serialize: ' . $valueType);
            }
            $tokens[] = $buffer;
        }
        return $tokens;
    }

//                        This is assoc array, using map

Recursively encodes data to OrientDB representation
@param array|OrientDBData $data Data to be encoded
@param bool $isAssoc Is keys needs to be included
@param bool $isArray Is this array or class
@throws OrientDBException
@return array Array of tokens


protected function stackGetLastKey()
    {
        $depth = false;
        for ($i = count($this->stackTT) - 1; $i >= 0; $i--) {
            if ($this->stackTT[$i] === self::TTYPE_NAME) {
                $depth = $i;
                break;
            }
        }
        if ($depth !== false) {
            return $this->stackTV[$depth];
        }
        return null;
    }

protected function stackGetLastKey ( ) { $ depth = false ; for ( $ i = count ( $ this -> stackTT ) - 1 ; $ i >= 0 ; $ i -- ) { if ( $ this -> stackTT [ $ i ] === self :: TTYPE_NAME ) { $ depth = $ i ; break ; } } if ( $ depth !== false ) { return $ this -> stackTV [ $ depth ] ; } return null ; }

Return string of last found key
@return string


public function prepare()
    {
        $this->addByte(chr($this->opType));
        if ($this->opType === self::DB_OPEN || $this->opType === self::CONNECT) {
            $this->currentTransactionID = -(++self::$transactionID);
        } else {
            if (in_array($this->opType, $this->parent->getCommandsRequiresConnect())) {
                $this->currentTransactionID = $this->parent->getSessionIDServer();
            } elseif (in_array($this->opType, $this->parent->getCommandsRequiresDBOpen())) {
                $this->currentTransactionID = $this->parent->getSessionIDDB();
            } else {
                throw new OrientDBWrongCommandException('Unknown command');
            }
        }
        $this->addInt($this->currentTransactionID);
    }

public
function
prepare
(
)
{
$
this
->
addByte
(
chr
(
$
this
->
opType
)
)
;
if
(
$
this
->
opType
===
self
::
DB_OPEN
||
$
this
->
opType
===
self
::
CONNECT
)
{
$
this
->
currentTransactionID
=
(
++
self
::
$
transactionID
)
;
}
else
{
if
(
in_array
(
$
this
->
opType
,
$
this
->
parent
->
getCommandsRequiresConnect
(
)
)
)
{
$
this
->
currentTransactionID
=
$
this
->
parent
->
getSessionIDServer
(
)
;
}
elseif
(
in_array
(
$
this
->
opType
,
$
this
->
parent
->
getCommandsRequiresDBOpen
(
)
)
)
{
$
this
->
currentTransactionID
=
$
this
->
parent
->
getSessionIDDB
(
)
;
}
else
{
throw
new
OrientDBWrongCommandException
(
'Unknown command'
)
;
}
}
$
this
->
addInt
(
$
this
->
currentTransactionID
)
;
}

Prepare command execution
@throws OrientDBWrongCommandException


public function execute()
    {
        $this->socket->debug = $this->debug;
        $this->socket->send($this->requestBytes);

        if (is_null($this->parent->protocolVersion)) {
            $this->debugCommand('protocol_version');
            $serverProtocolVersion = $this->readShort();
            $this->parent->setProtocolVersion($serverProtocolVersion);
        }
        if ($this->opType == self::DB_CLOSE) {
            // No incoming bytes
            return null;
        }

        $this->debugCommand('request_status');
        $this->requestStatus = $this->readByte();

        $this->debugCommand('TransactionID');
        $requestTransactionID = $this->readInt();
        if ($requestTransactionID !== $this->currentTransactionID) {
            throw new OrientDBException('Transaction ID mismatch');
        }

        if ($this->requestStatus === chr(OrientDBCommandAbstract::STATUS_SUCCESS)) {
            $data = $this->parseResponse();
            if ($this->opType === self::DB_OPEN) {
                $this->parent->setSessionIDDB($this->sessionID);
            } elseif ($this->opType === self::CONNECT) {
                $this->parent->setSessionIDServer($this->sessionID);
            }
            return $data;
        } elseif ($this->requestStatus === chr(OrientDBCommandAbstract::STATUS_ERROR)) {
            $exception = null;
            while ($this->readByte() === chr(OrientDBCommandAbstract::STATUS_ERROR)) {
                $this->debugCommand('exception_javaclass');
                $javaException = $this->readString();
                $this->debugCommand('exception_message');
                $javaExceptionDescr = $this->readString();
                $exception = new OrientDBException($javaException . ': ' . $javaExceptionDescr, 0, is_null($exception) ? null : $exception);
            }
            throw $exception;
        } else {
            throw new OrientDBException('Unknown error');
        }
    }

public
function
execute
(
)
{
$
this
->
socket
->
debug
=
$
this
->
debug
;
$
this
->
socket
->
send
(
$
this
->
requestBytes
)
;
if
(
is_null
(
$
this
->
parent
->
protocolVersion
)
)
{
$
this
->
debugCommand
(
'protocol_version'
)
;
$
serverProtocolVersion
=
$
this
->
readShort
(
)
;
$
this
->
parent
->
setProtocolVersion
(
$
serverProtocolVersion
)
;
}
if
(
$
this
->
opType
==
self
::
DB_CLOSE
)
{
// No incoming bytes
return
;
}
$
this
->
debugCommand
(
'request_status'
)
;
$
this
->
requestStatus
=
$
this
->
readByte
(
)
;
$
this
->
debugCommand
(
'TransactionID'
)
;
$
requestTransactionID
=
$
this
->
readInt
(
)
;
if
(
$
requestTransactionID
!==
$
this
->
currentTransactionID
)
{
throw
new
OrientDBException
(
'Transaction ID mismatch'
)
;
}
if
(
$
this
->
requestStatus
===
chr
(
OrientDBCommandAbstract
::
STATUS_SUCCESS
)
)
{
$
data
=
$
this
->
parseResponse
(
)
;
if
(
$
this
->
opType
===
self
::
DB_OPEN
)
{
$
this
->
parent
->
setSessionIDDB
(
$
this
->
sessionID
)
;
}
elseif
(
$
this
->
opType
===
self
::
CONNECT
)
{
$
this
->
parent
->
setSessionIDServer
(
$
this
->
sessionID
)
;
}
return
$
data
;
}
elseif
(
$
this
->
requestStatus
===
chr
(
OrientDBCommandAbstract
::
STATUS_ERROR
)
)
{
$
exception
=
;
while
(
$
this
->
readByte
(
)
===
chr
(
OrientDBCommandAbstract
::
STATUS_ERROR
)
)
{
$
this
->
debugCommand
(
'exception_javaclass'
)
;
$
javaException
=
$
this
->
readString
(
)
;
$
this
->
debugCommand
(
'exception_message'
)
;
$
javaExceptionDescr
=
$
this
->
readString
(
)
;
$
exception
=
new
OrientDBException
(
$
javaException
.
': '
.
$
javaExceptionDescr
,
0
,
is_null
(
$
exception
)
:
$
exception
)
;
}
throw
$
exception
;
}
else
{
throw
new
OrientDBException
(
'Unknown error'
)
;
}
}

Execute command by sending data to server, receive initial reply
@throws null|OrientDBException
@throws OrientDBException
@return mixed

Execute command by sending data to server receive initial reply


protected function readRaw($length)
    {
        $data = '';
        $dataLeft = $length;
        do {
            $data .= $this->socket->read($dataLeft);
            $dataLeft = $length - strlen($data);
        } while ($dataLeft > 0);
        return $data;
    }

protected function readRaw ( $ length ) { $ data = '' ; $ dataLeft = $ length ; do { $ data .= $ this -> socket -> read ( $ dataLeft ) ; $ dataLeft = $ length - strlen ( $ data ) ; } while ( $ dataLeft > 0 ) ; return $ data ; }

Read raw data from socket
@param int $length
@return string


protected function readLong()
    {
        // First of all, read 8 bytes, divided into hi and low parts
        $hi = unpack('N', $this->readRaw(4));
        $hi = reset($hi);
        $low = unpack('N', $this->readRaw(4));
        $low = reset($low);
        // Unpack 64-bit signed long
        return self::unpackI64($hi, $low);
    }

Read long from socket. Returns int
@throws OrientDBException
@return int


protected function readString()
    {
        $size = $this->readInt();
        if ($size === -1) {
            return null;
        }
        if ($size === 0) {
            return '';
        }
        return $this->readRaw($size);
    }

protected function readString ( ) { $ size = $ this -> readInt ( ) ; if ( $ size === - 1 ) { return null ; } if ( $ size === 0 ) { return '' ; } return $ this -> readRaw ( $ size ) ; }

Read string from socket, including its length
@return string

Read string from socket including its length


protected function readBytes()
    {
        $size = $this->readInt();
        if ($size === -1) {
            return null;
        }
        if ($size === 0) {
            return '';
        }
        return $this->readRaw($size);
    }

protected function readBytes ( ) { $ size = $ this -> readInt ( ) ; if ( $ size === - 1 ) { return null ; } if ( $ size === 0 ) { return '' ; } return $ this -> readRaw ( $ size ) ; }

Read bytes stream from socket, including int length
@return string

Read bytes stream from socket including int length


protected function readRecord()
    {

        $this->debugCommand('record_marker');
        $marker = $this->readShort();
        /**
         * @see enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryProtocol.java
         */

        // -2=no record
        if ($marker == -2) {
            // no record
            return false;
        }

        // -3=Only recordID
        if ($marker == -3) {
            // only recordID
            $this->debugCommand('record_clusterID');
            $clusterID = $this->readShort();
            $this->debugCommand('record_position');
            $recordPos = $this->readLong();
            return new OrientDBTypeLink($clusterID, $recordPos);
        }

        $record = new OrientDBRecord();
        $this->debugCommand('record_type');
        $record->type = $this->readByte();
        $this->debugCommand('record_clusterID');
        $record->clusterID = $this->readShort();
        $this->debugCommand('record_position');
        $record->recordPos = $this->readLong();
        $this->debugCommand('record_version');
        $record->version = $this->readInt();
        $this->debugCommand('record_content');
        $record->content = $this->readBytes();

        return $record;
    }

Read entire record from socket
@return boolean|OrientDBTypeLink|OrientDBRecord


protected function addBytes($string)
    {
        if ($string instanceof OrientDBRecord) {
            $string = (string) $string;
        }
        $this->addInt(strlen($string));
        $this->requestBytes .= $string;
    }

protected function addBytes ( $ string ) { if ( $ string instanceof OrientDBRecord ) { $ string = ( string ) $ string ; } $ this -> addInt ( strlen ( $ string ) ) ; $ this -> requestBytes .= $ string ; }

Add byte stream to outgoing data. Length is calculated automatically
@param string $string

Add byte stream to outgoing data . Length is calculated automatically


public static function unpackI64($hi, $low)
    {
        // Packing is:
        // OrientDBHelpers::hexDump(pack('NN', $int >> 32, $int & 0xFFFFFFFF));

        // If x64 system, just shift hi bytes to the left, add low bytes. Piece of cake.
        if (PHP_INT_SIZE === 8) {
            return ($hi << 32) + $low;
        }

        // x32
        // Check if long could fit into int
        $hiComplement = self::convertComplementInt($hi);
        if ($hiComplement === 0) {
            // Hi part is 0, low will fit in x32 int
            return $low;
        } elseif ($hiComplement === -1) {
            // Hi part is negative, so we just can convert low part
            if ($low >= 0x80000000) {
                // Check if low part is lesser than minimum 32 bit signed integer
                return self::convertComplementInt($low);
            }
        }

        // x32 string with bc_match
        // Check if module is available
        if (!extension_loaded('bcmath')) {
            throw new OrientDBException('Required bcmath module to continue');
        }

        // Sign char
        $sign = '';
        $lastBit = 0;
        // This is negative number
        if ($hiComplement < 0) {
            $hi = ~$hi;
            $low = ~$low;
            $lastBit = 1;
            $sign = '-';
        }

        // Format bytes properly
        $hi = sprintf('%u', $hi);
        $low = sprintf('%u', $low);

        // Do math
        $temp = bcmul($hi, '4294967296');
        $temp = bcadd($low, $temp);
        $temp = bcadd($temp, $lastBit);
        return $sign . $temp;
    }

Unpacks 64 bits signed long
@static
@param $hi int Hi bytes of long
@param $low int Low bytes of long
@throws OrientDBException
@return int|string


public function resetData()
    {
        $this->data = new OrientDBData($this);
        $this->content = null;
        $this->isParsed = true;
        $this->recordPos = null;
        $this->recordID = null;
        $this->version = null;
    }

public function resetData ( ) { $ this -> data = new OrientDBData ( $ this ) ; $ this -> content = null ; $ this -> isParsed = true ; $ this -> recordPos = null ; $ this -> recordID = null ; $ this -> version = null ; }

Resets Record data, keeping className and clusterID intact
@return void

Resets Record data keeping className and clusterID intact


public function getProps()
    {
        $sortedChildFusionKeys = $this->sortNestedFusionKeys();

        $props = [];
        foreach ($sortedChildFusionKeys as $key) {
            try {
                $props[$key] = $this->fusionValue($key);
            } catch (\Exception $e) {
                $props[$key] = $this->runtime->handleRenderingException($this->path . '/' . $key, $e);
            }
        }

        return $props;
    }

public function getProps ( ) { $ sortedChildFusionKeys = $ this -> sortNestedFusionKeys ( ) ; $ props = [ ] ; foreach ( $ sortedChildFusionKeys as $ key ) { try { $ props [ $ key ] = $ this -> fusionValue ( $ key ) ; } catch ( \ Exception $ e ) { $ props [ $ key ] = $ this -> runtime -> handleRenderingException ( $ this -> path . '/' . $ key , $ e ) ; } } return $ props ; }

Get the component props as an associative array

@return array


public function renderComponent(array $props)
    {
        $context = $this->runtime->getCurrentContext();
        $context['props'] = $props;
        $this->runtime->pushContextArray($context);
        $result = $this->runtime->render($this->path . '/renderer');
        $this->runtime->popContext();

        return $result;
    }

public function renderComponent ( array $ props ) { $ context = $ this -> runtime -> getCurrentContext ( ) ; $ context [ 'props' ] = $ props ; $ this -> runtime -> pushContextArray ( $ context ) ; $ result = $ this -> runtime -> render ( $ this -> path . '/renderer' ) ; $ this -> runtime -> popContext ( ) ; return $ result ; }

Render the component with the given props

@param array $props
@return void|string


public function classNames(...$arguments)
    {
        $classNames = [];
        foreach ($arguments as $argument) {
            if ((bool)$argument === true) {
                if (is_array($argument)) {
                    $keys = array_keys($argument);
                    $isAssoc = array_keys($keys) !== $keys;
                    if ($isAssoc) {
                        foreach ($argument as $className => $condition) {
                            if ((bool)$condition === true) {
                                $classNames[] = (string)$className;
                            }
                        }
                    } else {
                        foreach ($argument as $className) {
                            if (is_scalar($className) && !!is_bool($condition) && (bool)$className === true) {
                                $classNames[] = (string)$className;
                            }
                        }
                    }
                } elseif (is_scalar($argument) && !is_bool($argument)) {
                    $classNames[] = (string)$argument;
                }
            }
        }
        return implode(' ', $classNames);
    }

public
function
classNames
(
...
$
arguments
)
{
$
classNames
=
[
]
;
foreach
(
$
arguments
as
$
argument
)
{
if
(
(
bool
)
$
argument
===
true
)
{
if
(
is_array
(
$
argument
)
)
{
$
keys
=
array_keys
(
$
argument
)
;
$
isAssoc
=
array_keys
(
$
keys
)
!==
$
keys
;
if
(
$
isAssoc
)
{
foreach
(
$
argument
as
$
className
=>
$
condition
)
{
if
(
(
bool
)
$
condition
===
true
)
{
$
classNames
[
]
=
(
string
)
$
className
;
}
}
}
else
{
foreach
(
$
argument
as
$
className
)
{
if
(
is_scalar
(
$
className
)
&&
!
!
is_bool
(
$
condition
)
&&
(
bool
)
$
className
===
true
)
{
$
classNames
[
]
=
(
string
)
$
className
;
}
}
}
}
elseif
(
is_scalar
(
$
argument
)
&&
!
is_bool
(
$
argument
)
)
{
$
classNames
[
]
=
(
string
)
$
argument
;
}
}
}
return
implode
(
' '
,
$
classNames
)
;
}

Render the arguments as class-names after applying some rules

@param mixed $arguments [optional] class-name rules
argument rules:
- falsy: (null, '', [], {}) -> not rendered
- array: all items that are scalar and truthy are rendered as class-name
- object: keys that have a truthy values are rendered as class-name
- scalar: is cast to string and rendered as class-name

Render the arguments as class - names after applying some rules


public function getIdealIssuers()
    {
        try {
            $response = $this->getHttpClient()
                ->method(Http::GET)
                ->uri($this->baseUrl . 'ideal/issuers/')
                ->send();

            if ($response->hasErrors()) {
                throw new \Exception($response->raw_body, $response->code);
            }

            return Issuers::fromArray($response->body);
        } catch (\Exception $exception) {
            throw new ClientException(
                'An error occurred while processing the request: '.$exception->getMessage(),
                $exception->getCode(),
                $exception
            );
        }
    }

Get possible iDEAL issuers.

@return Issuers


public function getAllowedProducts()
    {
        try {
            $response = $this->getHttpClient()
                ->method(Http::GET)
                ->uri($this->baseUrl . 'merchants/self/projects/self/')
                ->send();

            if ($response->hasErrors()) {
                throw new \Exception($response->raw_body, $response->code);
            }

            return $this->processProducts($response->body);
        } catch (\Exception $exception) {
            return [];
        }
    }

public function getAllowedProducts ( ) { try { $ response = $ this -> getHttpClient ( ) -> method ( Http :: GET ) -> uri ( $ this -> baseUrl . 'merchants/self/projects/self/' ) -> send ( ) ; if ( $ response -> hasErrors ( ) ) { throw new \ Exception ( $ response -> raw_body , $ response -> code ) ; } return $ this -> processProducts ( $ response -> body ) ; } catch ( \ Exception $ exception ) { return [ ] ; } }

Get allowed payment methods.

@return array


private function processProducts($details)
    {
        $result = array();

        if (!array_key_exists('permissions', $details)) {
            return $result;
        }

        $products_to_check = array(
            'ideal' => 'ideal',
            'bank-transfer' => 'banktransfer',
            'bancontact' => 'bancontact',
            'cash-on-delivery' => 'cashondelivery',
            'credit-card' => 'creditcard',
            'paypal' => 'paypal',
            'homepay' => 'homepay',
            'klarna' => 'klarna',
            'sofort' => 'sofort',
            'payconiq' => 'payconiq',
            'afterpay' => 'afterpay'
        );

        foreach ($products_to_check as $permission_id => $id) {
            if (array_key_exists('/payment-methods/'.$permission_id.'/', $details['permissions']) &&
                array_key_exists('POST', $details['permissions']['/payment-methods/'.$permission_id.'/']) &&
                $details['permissions']['/payment-methods/'.$permission_id.'/']['POST']
            ) {
                $result[] = $id;
            }
        }

        return $result;
    }

private function processProducts ( $ details ) { $ result = array ( ) ; if ( ! array_key_exists ( 'permissions' , $ details ) ) { return $ result ; } $ products_to_check = array ( 'ideal' => 'ideal' , 'bank-transfer' => 'banktransfer' , 'bancontact' => 'bancontact' , 'cash-on-delivery' => 'cashondelivery' , 'credit-card' => 'creditcard' , 'paypal' => 'paypal' , 'homepay' => 'homepay' , 'klarna' => 'klarna' , 'sofort' => 'sofort' , 'payconiq' => 'payconiq' , 'afterpay' => 'afterpay' ) ; foreach ( $ products_to_check as $ permission_id => $ id ) { if ( array_key_exists ( '/payment-methods/' . $ permission_id . '/' , $ details [ 'permissions' ] ) && array_key_exists ( 'POST' , $ details [ 'permissions' ] [ '/payment-methods/' . $ permission_id . '/' ] ) && $ details [ 'permissions' ] [ '/payment-methods/' . $ permission_id . '/' ] [ 'POST' ] ) { $ result [ ] = $ id ; } } return $ result ; }

Process the API response with allowed payment methods.

@param array $details
@return array

Process the API response with allowed payment methods .


public function createIdealOrder(
        $amount,
        $currency,
        $issuerId,
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return $this->postOrder(
            Order::createWithIdeal(
                $amount,
                $currency,
                $issuerId,
                $description,
                $merchantOrderId,
                $returnUrl,
                $expirationPeriod,
                $customer,
                $extra,
                $webhookUrl
            )
        );
    }

public function createIdealOrder ( $ amount , $ currency , $ issuerId , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return $ this -> postOrder ( Order :: createWithIdeal ( $ amount , $ currency , $ issuerId , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ) ; }

Create a new iDEAL order.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param string $issuerId The SWIFT/BIC code of the iDEAL issuer.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration
@param array $customer Customer information.
@param array $extra Extra information.

@return Order The newly created order.


public function createSepaOrder(
        $amount,
        $currency,
        array $paymentMethodDetails = [],
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return $this->postOrder(
            Order::createWithSepa(
                $amount,
                $currency,
                $paymentMethodDetails,
                $description,
                $merchantOrderId,
                $returnUrl,
                $expirationPeriod,
                $customer,
                $extra,
                $webhookUrl
            )
        );
    }

public function createSepaOrder ( $ amount , $ currency , array $ paymentMethodDetails = [ ] , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return $ this -> postOrder ( Order :: createWithSepa ( $ amount , $ currency , $ paymentMethodDetails , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ) ; }

Create a new SEPA order.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param array $paymentMethodDetails An array of extra payment method details.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration
@param array $customer Customer information.
@param array $extra Extra information.

@return Order The newly created order.


public function createSofortOrder(
        $amount,
        $currency,
        array $paymentMethodDetails = [],
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return $this->postOrder(
            Order::createWithSofort(
                $amount,
                $currency,
                $paymentMethodDetails,
                $description,
                $merchantOrderId,
                $returnUrl,
                $expirationPeriod,
                $customer,
                $extra,
                $webhookUrl
            )
        );
    }

public function createSofortOrder ( $ amount , $ currency , array $ paymentMethodDetails = [ ] , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return $ this -> postOrder ( Order :: createWithSofort ( $ amount , $ currency , $ paymentMethodDetails , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ) ; }

Create a new SOFORT order.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param array $paymentMethodDetails An array of extra payment method details.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration
@param array $customer Customer information.
@param array $extra Extra information.

@return Order The newly created order.


public function createPayconicOrder(
        $amount,
        $currency,
        array $paymentMethodDetails = [],
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return $this->postOrder(
            Order::createWithPayconiq(
                $amount,
                $currency,
                $paymentMethodDetails,
                $description,
                $merchantOrderId,
                $returnUrl,
                $expirationPeriod,
                $customer,
                $extra,
                $webhookUrl
            )
        );
    }

public function createPayconicOrder ( $ amount , $ currency , array $ paymentMethodDetails = [ ] , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return $ this -> postOrder ( Order :: createWithPayconiq ( $ amount , $ currency , $ paymentMethodDetails , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ) ; }

Create a new Payconiq order.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param array $paymentMethodDetails An array of extra payment method details.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration
@param array $customer Customer information.
@param array $extra Extra information.
@param string $webhookUrl The webhook URL.

@return Order The newly created order.


public function createCreditCardOrder(
        $amount,
        $currency,
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return $this->postOrder(
            Order::createWithCreditCard(
                $amount,
                $currency,
                $description,
                $merchantOrderId,
                $returnUrl,
                $expirationPeriod,
                $customer,
                $extra,
                $webhookUrl
            )
        );
    }

public function createCreditCardOrder ( $ amount , $ currency , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return $ this -> postOrder ( Order :: createWithCreditCard ( $ amount , $ currency , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ) ; }

Create a new credit card order.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration
@param array $customer Customer information.
@param array $extra Extra information.

@return Order The newly created order.


public function createBancontactOrder(
        $amount,
        $currency,
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return $this->postOrder(
            Order::createWithBancontact(
                $amount,
                $currency,
                $description,
                $merchantOrderId,
                $returnUrl,
                $expirationPeriod,
                $customer,
                $extra,
                $webhookUrl
            )
        );
    }

public function createBancontactOrder ( $ amount , $ currency , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return $ this -> postOrder ( Order :: createWithBancontact ( $ amount , $ currency , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ) ; }

Create a new Bancontact order.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration
@param array $customer Customer information.
@param array $extra Extra information.

@return Order The newly created order.


public function createCashOnDeliveryOrder(
        $amount,
        $currency,
        array $paymentMethodDetails = [],
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return $this->postOrder(
            Order::createWithCod(
                $amount,
                $currency,
                $paymentMethodDetails,
                $description,
                $merchantOrderId,
                $returnUrl,
                $expirationPeriod,
                $customer,
                $extra,
                $webhookUrl
            )
        );
    }

public function createCashOnDeliveryOrder ( $ amount , $ currency , array $ paymentMethodDetails = [ ] , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return $ this -> postOrder ( Order :: createWithCod ( $ amount , $ currency , $ paymentMethodDetails , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ) ; }

Create a new Cash On Delivery order.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param array $paymentMethodDetails An array of extra payment method details.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration
@param array $customer Customer information.
@param array $extra Extra information.
@param string $webhookUrl The webhook URL.

@return Order The newly created order.


public function createKlarnaOrder(
        $amount,
        $currency,
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null,
        $orderLines = null
    ) {
        return $this->postOrder(
            Order::createWithKlarna(
                $amount,
                $currency,
                $description,
                $merchantOrderId,
                $returnUrl,
                $expirationPeriod,
                $customer,
                $extra,
                $webhookUrl,
                $orderLines
            )
        );
    }

public function createKlarnaOrder ( $ amount , $ currency , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null , $ orderLines = null ) { return $ this -> postOrder ( Order :: createWithKlarna ( $ amount , $ currency , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl , $ orderLines ) ) ; }

Create a new Klarna order.

@param integer $amount            Amount in cents.
@param string  $currency          A valid currency code.
@param string  $description       A description of the order.
@param string  $merchantOrderId   A merchant-defined order identifier.
@param string  $returnUrl         The return URL.
@param string  $expirationPeriod  The expiration period as an ISO 8601 duration
@param array   $customer          Customer information.
@param array   $extra             Extra information.
@param string  $webhookUrl        The webhook URL.
@param array   $orderLines        Order lines

@return Order The newly created order.


public function createPaypalOrder(
        $amount,
        $currency,
        array $paymentMethodDetails = [],
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return $this->postOrder(
            Order::createWithPaypal(
                $amount,
                $currency,
                $paymentMethodDetails,
                $description,
                $merchantOrderId,
                $returnUrl,
                $expirationPeriod,
                $customer,
                $extra,
                $webhookUrl
            )
        );
    }

public function createPaypalOrder ( $ amount , $ currency , array $ paymentMethodDetails = [ ] , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return $ this -> postOrder ( Order :: createWithPaypal ( $ amount , $ currency , $ paymentMethodDetails , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ) ; }

Create a new PayPal order.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param array $paymentMethodDetails An array of extra payment method details.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration
@param array $customer Customer information.
@param array $extra Extra information.

@return Order The newly created order.


public function createHomepayOrder(
        $amount,
        $currency,
        array $paymentMethodDetails = [],
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return $this->postOrder(
            Order::createWithHomepay(
                $amount,
                $currency,
                $paymentMethodDetails,
                $description,
                $merchantOrderId,
                $returnUrl,
                $expirationPeriod,
                $customer,
                $extra,
                $webhookUrl
            )
        );
    }

public function createHomepayOrder ( $ amount , $ currency , array $ paymentMethodDetails = [ ] , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return $ this -> postOrder ( Order :: createWithHomepay ( $ amount , $ currency , $ paymentMethodDetails , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ) ; }

Create a new Home'Pay order.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param array $paymentMethodDetails An array of extra payment method details.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration
@param array $customer Customer information.
@param array $extra Extra information.

@return Order The newly created order.


public function createAfterPayOrder(
        $amount,
        $currency,
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null,
        $orderLines = null
    ) {
        return $this->postOrder(
            Order::createWithAfterPay(
                $amount,
                $currency,
                $description,
                $merchantOrderId,
                $returnUrl,
                $expirationPeriod,
                $customer,
                $extra,
                $webhookUrl,
                $orderLines
            )
        );
    }

public function createAfterPayOrder ( $ amount , $ currency , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null , $ orderLines = null ) { return $ this -> postOrder ( Order :: createWithAfterPay ( $ amount , $ currency , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl , $ orderLines ) ) ; }

Create a new AfterPay order.

@param integer $amount            Amount in cents.
@param string  $currency          A valid currency code.
@param string  $description       A description of the order.
@param string  $merchantOrderId   A merchant-defined order identifier.
@param string  $returnUrl         The return URL.
@param string  $expirationPeriod  The expiration period as an ISO 8601 duration
@param array   $customer          Customer information.
@param array   $extra             Extra information.
@param string  $webhookUrl        The webhook URL.
@param array   $orderLines        Order lines

@return Order The newly created order.


public function createOrder(
        $amount,
        $currency,
        $paymentMethod,
        array $paymentMethodDetails = [],
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return $this->postOrder(
            Order::create(
                $amount,
                $currency,
                $paymentMethod,
                $paymentMethodDetails,
                $description,
                $merchantOrderId,
                $returnUrl,
                $expirationPeriod,
                $customer,
                $extra,
                $webhookUrl
            )
        );
    }

public function createOrder ( $ amount , $ currency , $ paymentMethod , array $ paymentMethodDetails = [ ] , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return $ this -> postOrder ( Order :: create ( $ amount , $ currency , $ paymentMethod , $ paymentMethodDetails , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ) ; }

Create a new order.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param string $paymentMethod The payment method to use.
@param array $paymentMethodDetails An array of extra payment method details.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration
@param array $customer Customer information.
@param array $extra Extra information.
@param string $webhookUrl The webhook URL.

@return Order The newly created order.


public function getOrder($id)
    {
        try {
            $response = $this->getHttpClient()
                ->method(Http::GET)
                ->uri($this->baseUrl . 'orders/' . $id . '/')
                ->send();

            if ($response->hasErrors()) {
                throw new \Exception($response->raw_body, $response->code);
            }

            return Order::fromArray($response->body);
        } catch (\Exception $exception) {
            if ($exception->getCode() == 404) {
                throw new OrderNotFoundException('No order with that ID was found.', 404, $exception);
            }
            throw new ClientException(
                'An error occurred while getting the order: '.$exception->getMessage(),
                $exception->getCode(),
                $exception
            );
        }
    }

Get a single order.

@param string $id The order ID.
@return Order


private function postOrder(Order $order)
    {
        try {
            $response = $this->getHttpClient()
                ->method(Http::POST)
                ->uri($this->baseUrl . 'orders/')
                ->timeout(30)
                ->sends(Mime::JSON)
                ->body(ArrayFunctions::withoutNullValues($order->toArray()))
                ->send();

            if ($response->hasErrors()) {
                throw new \Exception($response->raw_body, $response->code);
            }

            return Order::fromArray($response->body);
        } catch (\Exception $exception) {
            throw new ClientException(
                'An error occurred while posting the order: '.$exception->getMessage(),
                $exception->getCode(),
                $exception
            );
        }
    }

Post a new order.

@param Order $order
@return Order


public function setOrderCapturedStatus(Order $order)
    {
        try {
            $transactionId = $order->transactions()->current()->id()->toString();
            $response = $this->getHttpClient()
                ->method(Http::POST)
                ->uri($this->baseUrl . 'orders/' . $order->id() . '/transactions/'. $transactionId . '/captures/')
                ->timeout(30)
                ->sends(Mime::JSON)
                ->send();

            if ($response->hasErrors()) {
                throw new \Exception($response->raw_body, $response->code);
            }

            return Transaction::fromArray($response->body);
        } catch (\Exception $exception) {
            if ($exception->getCode() == 404) {
                throw new OrderNotFoundException('No order with that ID was found.', 404, $exception);
            }
            throw new ClientException(
                'An error occurred while updating the order: '.$exception->getMessage(),
                $exception->getCode(),
                $exception
            );
        }
    }

update the order status to captured

@param  Order $order
@throws OrderNotFoundException
@throws ClientException
@return Transaction


public static function createWithIdeal(
        $amount,
        $currency,
        $issuerId,
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return static::create(
            $amount,
            $currency,
            PaymentMethod::IDEAL,
            ['issuer_id' => $issuerId],
            $description,
            $merchantOrderId,
            $returnUrl,
            $expirationPeriod,
            $customer,
            $extra,
            $webhookUrl
        );
    }

public static function createWithIdeal ( $ amount , $ currency , $ issuerId , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return static :: create ( $ amount , $ currency , PaymentMethod :: IDEAL , [ 'issuer_id' => $ issuerId ] , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ; }

Create a new Order with the iDEAL payment method.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param string $issuerId The SWIFT/BIC code of the iDEAL issuer.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration
@param array $customer Customer information.
@param array $extra Extra information.
@param string $webhookUrl The webhook URL.

@return Order

Create a new Order with the iDEAL payment method .


public static function createWithCreditCard(
        $amount,
        $currency,
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return static::create(
            $amount,
            $currency,
            PaymentMethod::CREDIT_CARD,
            [],
            $description,
            $merchantOrderId,
            $returnUrl,
            $expirationPeriod,
            $customer,
            $extra,
            $webhookUrl
        );
    }

public static function createWithCreditCard ( $ amount , $ currency , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return static :: create ( $ amount , $ currency , PaymentMethod :: CREDIT_CARD , [ ] , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ; }

Create a new Order with the credit card payment method.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration
@param array $customer Customer information.
@param array $extra Extra information.
@param string $webhookUrl The webhook URL.

@return Order

Create a new Order with the credit card payment method .


public static function createWithSepa(
        $amount,
        $currency,
        array $paymentMethodDetails = [],
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return static::create(
            $amount,
            $currency,
            PaymentMethod::BANK_TRANSFER,
            $paymentMethodDetails,
            $description,
            $merchantOrderId,
            $returnUrl,
            $expirationPeriod,
            $customer,
            $extra,
            $webhookUrl
        );
    }

public static function createWithSepa ( $ amount , $ currency , array $ paymentMethodDetails = [ ] , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return static :: create ( $ amount , $ currency , PaymentMethod :: BANK_TRANSFER , $ paymentMethodDetails , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ; }

Create a new Order with the SEPA payment method.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param array $paymentMethodDetails An array of extra payment method details.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration.
@param array $customer Customer information
@param array $extra Extra information.
@param string $webhookUrl The webhook URL.

@return Order

Create a new Order with the SEPA payment method .


public static function createWithSofort(
        $amount,
        $currency,
        array $paymentMethodDetails = [],
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return static::create(
            $amount,
            $currency,
            PaymentMethod::SOFORT,
            $paymentMethodDetails,
            $description,
            $merchantOrderId,
            $returnUrl,
            $expirationPeriod,
            $customer,
            $extra,
            $webhookUrl
        );
    }

public static function createWithSofort ( $ amount , $ currency , array $ paymentMethodDetails = [ ] , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return static :: create ( $ amount , $ currency , PaymentMethod :: SOFORT , $ paymentMethodDetails , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ; }

Create a new Order with the SOFORT payment method.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param array $paymentMethodDetails An array of extra payment method details.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration.
@param array $customer Customer information.
@param array $extra Extra information.
@param string $webhookUrl The webhook URL.

@return Order

Create a new Order with the SOFORT payment method .


public static function createWithBancontact(
        $amount,
        $currency,
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return static::create(
            $amount,
            $currency,
            PaymentMethod::BANCONTACT,
            [],
            $description,
            $merchantOrderId,
            $returnUrl,
            $expirationPeriod,
            $customer,
            $extra,
            $webhookUrl
        );
    }

public static function createWithBancontact ( $ amount , $ currency , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return static :: create ( $ amount , $ currency , PaymentMethod :: BANCONTACT , [ ] , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ; }

Create a new Order with the Bancontact payment method.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration.
@param array $customer Customer information.
@param array $extra Extra information.
@param string $webhookUrl The webhook URL.

@return Order

Create a new Order with the Bancontact payment method .


public static function createWithPaypal(
        $amount,
        $currency,
        array $paymentMethodDetails = [],
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return static::create(
            $amount,
            $currency,
            PaymentMethod::PAYPAL,
            $paymentMethodDetails,
            $description,
            $merchantOrderId,
            $returnUrl,
            $expirationPeriod,
            $customer,
            $extra,
            $webhookUrl
        );
    }

public static function createWithPaypal ( $ amount , $ currency , array $ paymentMethodDetails = [ ] , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return static :: create ( $ amount , $ currency , PaymentMethod :: PAYPAL , $ paymentMethodDetails , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ; }

Create a new Order with the Paypal payment method.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param array $paymentMethodDetails An array of extra payment method details.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration.
@param array $customer Customer information.
@param array $extra Extra information.
@param string $webhookUrl The webhook URL.

@return Order

Create a new Order with the Paypal payment method .


public static function createWithHomepay(
        $amount,
        $currency,
        array $paymentMethodDetails = [],
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return static::create(
            $amount,
            $currency,
            PaymentMethod::HOMEPAY,
            $paymentMethodDetails,
            $description,
            $merchantOrderId,
            $returnUrl,
            $expirationPeriod,
            $customer,
            $extra,
            $webhookUrl
        );
    }

public static function createWithHomepay ( $ amount , $ currency , array $ paymentMethodDetails = [ ] , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return static :: create ( $ amount , $ currency , PaymentMethod :: HOMEPAY , $ paymentMethodDetails , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ; }

Create a new Order with the HomePay payment method.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param array $paymentMethodDetails An array of extra payment method details.
@param string $description A description of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration.
@param array $customer Customer information.
@param array $extra Extra information.
@param string $webhookUrl The webhook URL.

@return Order

Create a new Order with the HomePay payment method .


public static function createWithPayconiq(
        $amount,
        $currency,
        array $paymentMethodDetails = [],
        $description = null,
        $merchantOrderId = null,
        $returnUrl = null,
        $expirationPeriod = null,
        $customer = null,
        $extra = null,
        $webhookUrl = null
    ) {
        return static::create(
            $amount,
            $currency,
            PaymentMethod::PAYCONIQ,
            $paymentMethodDetails,
            $description,
            $merchantOrderId,
            $returnUrl,
            $expirationPeriod,
            $customer,
            $extra,
            $webhookUrl
        );
    }

public static function createWithPayconiq ( $ amount , $ currency , array $ paymentMethodDetails = [ ] , $ description = null , $ merchantOrderId = null , $ returnUrl = null , $ expirationPeriod = null , $ customer = null , $ extra = null , $ webhookUrl = null ) { return static :: create ( $ amount , $ currency , PaymentMethod :: PAYCONIQ , $ paymentMethodDetails , $ description , $ merchantOrderId , $ returnUrl , $ expirationPeriod , $ customer , $ extra , $ webhookUrl ) ; }

Create a new Order with the Payconiq payment method.

@param integer $amount Amount in cents.
@param string $currency A valid currency code.
@param array $paymentMethodDetails An array of extra payment method details.
@param string $description A descriptionyconiq of the order.
@param string $merchantOrderId A merchant-defined order identifier.
@param string $returnUrl The return URL.
@param string $expirationPeriod The expiration period as an ISO 8601 duration.
@param array $customer Customer information.
@param array $extra Extra information.
@param string $webhookUrl The webhook URL.

@return Order

Create a new Order with the Payconiq payment method .