repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/ConfigurationService.php | ConfigurationService.loadConfigurationByFilename | public function loadConfigurationByFilename($filename)
{
// initialize the DOMDocument with the configuration file to be validated
$configurationFile = new \DOMDocument();
$configurationFile->load($filename);
// substitute xincludes
$configurationFile->xinclude(LIBXML_SCHEMA_CREATE);
// create a DOMElement with the base.dir configuration
$paramElement = $configurationFile->createElement('param', APPSERVER_BP);
$paramElement->setAttribute('name', DirectoryKeys::BASE);
$paramElement->setAttribute('type', ParamNode::TYPE_STRING);
// create an XPath instance
$xpath = new \DOMXpath($configurationFile);
$xpath->registerNamespace('a', 'http://www.appserver.io/appserver');
// for node data in a selected id
$baseDirParam = $xpath->query(sprintf('/a:appserver/a:params/a:param[@name="%s"]', DirectoryKeys::BASE));
if ($baseDirParam->length === 0) {
// load the <params> node
$paramNodes = $xpath->query('/a:appserver/a:params');
// load the first item => the node itself
if ($paramsNode = $paramNodes->item(0)) {
// append the base.dir DOMElement
$paramsNode->appendChild($paramElement);
} else {
// throw an exception, because we can't find a mandatory node
throw new \Exception('Can\'t find /appserver/params node');
}
}
// create a new DOMDocument with the merge content => necessary because else, schema validation fails!!
$doc = new \DOMDocument();
$doc->loadXML($configurationFile->saveXML());
// return the XML document
return $doc;
} | php | public function loadConfigurationByFilename($filename)
{
// initialize the DOMDocument with the configuration file to be validated
$configurationFile = new \DOMDocument();
$configurationFile->load($filename);
// substitute xincludes
$configurationFile->xinclude(LIBXML_SCHEMA_CREATE);
// create a DOMElement with the base.dir configuration
$paramElement = $configurationFile->createElement('param', APPSERVER_BP);
$paramElement->setAttribute('name', DirectoryKeys::BASE);
$paramElement->setAttribute('type', ParamNode::TYPE_STRING);
// create an XPath instance
$xpath = new \DOMXpath($configurationFile);
$xpath->registerNamespace('a', 'http://www.appserver.io/appserver');
// for node data in a selected id
$baseDirParam = $xpath->query(sprintf('/a:appserver/a:params/a:param[@name="%s"]', DirectoryKeys::BASE));
if ($baseDirParam->length === 0) {
// load the <params> node
$paramNodes = $xpath->query('/a:appserver/a:params');
// load the first item => the node itself
if ($paramsNode = $paramNodes->item(0)) {
// append the base.dir DOMElement
$paramsNode->appendChild($paramElement);
} else {
// throw an exception, because we can't find a mandatory node
throw new \Exception('Can\'t find /appserver/params node');
}
}
// create a new DOMDocument with the merge content => necessary because else, schema validation fails!!
$doc = new \DOMDocument();
$doc->loadXML($configurationFile->saveXML());
// return the XML document
return $doc;
} | [
"public",
"function",
"loadConfigurationByFilename",
"(",
"$",
"filename",
")",
"{",
"// initialize the DOMDocument with the configuration file to be validated",
"$",
"configurationFile",
"=",
"new",
"\\",
"DOMDocument",
"(",
")",
";",
"$",
"configurationFile",
"->",
"load"... | Loads the configuration from the passed filename.
@param string $filename The filename to load the configuration from
@return \DOMDocument The parsed Configuration
@throws \Exception | [
"Loads",
"the",
"configuration",
"from",
"the",
"passed",
"filename",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/ConfigurationService.php#L134-L175 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/ConfigurationService.php | ConfigurationService.validateFile | public function validateFile($fileName, $schemaFile = null, $failOnErrors = false)
{
// if we did not get a schema file we have to check if we know which one to use
if (is_null($schemaFile)) {
$this->findSchemaFile($fileName);
$schemaFile = $this->schemaFile;
}
// validate the passed configuration file
ConfigurationUtils::singleton()->validateFile($fileName, $schemaFile, $failOnErrors);
} | php | public function validateFile($fileName, $schemaFile = null, $failOnErrors = false)
{
// if we did not get a schema file we have to check if we know which one to use
if (is_null($schemaFile)) {
$this->findSchemaFile($fileName);
$schemaFile = $this->schemaFile;
}
// validate the passed configuration file
ConfigurationUtils::singleton()->validateFile($fileName, $schemaFile, $failOnErrors);
} | [
"public",
"function",
"validateFile",
"(",
"$",
"fileName",
",",
"$",
"schemaFile",
"=",
"null",
",",
"$",
"failOnErrors",
"=",
"false",
")",
"{",
"// if we did not get a schema file we have to check if we know which one to use",
"if",
"(",
"is_null",
"(",
"$",
"schem... | Will validate a given file against a schema.
This method supports several validation mechanisms for different file types.
Will return true if validation passes, false otherwise.
A specific schema file to use might be passed as well, if none is given the tester tries to choose the right one
@param string $fileName Name of the file to validate
@param string|null $schemaFile The specific schema file to validate against (optional)
@param boolean $failOnErrors If the validation should fail on error (optional)
@return void
@throws \Exception If aren't able to validate this file type | [
"Will",
"validate",
"a",
"given",
"file",
"against",
"a",
"schema",
".",
"This",
"method",
"supports",
"several",
"validation",
"mechanisms",
"for",
"different",
"file",
"types",
".",
"Will",
"return",
"true",
"if",
"validation",
"passes",
"false",
"otherwise",
... | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/ConfigurationService.php#L203-L214 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/ConfigurationService.php | ConfigurationService.validateXml | public function validateXml(\DOMDocument $domDocument, $schemaFile = null, $failOnErrors = false)
{
// if we got a specific schema file we will use it, otherwise we will use the one we got globally
$schemaFileName = $this->schemaFile;
if (!is_null($schemaFile)) {
$schemaFileName = $schemaFile;
}
// validate the passed DOM document
ConfigurationUtils::singleton()->validateXml($domDocument, $schemaFileName, $failOnErrors);
// return TRUE if validation has been successfull
return true;
} | php | public function validateXml(\DOMDocument $domDocument, $schemaFile = null, $failOnErrors = false)
{
// if we got a specific schema file we will use it, otherwise we will use the one we got globally
$schemaFileName = $this->schemaFile;
if (!is_null($schemaFile)) {
$schemaFileName = $schemaFile;
}
// validate the passed DOM document
ConfigurationUtils::singleton()->validateXml($domDocument, $schemaFileName, $failOnErrors);
// return TRUE if validation has been successfull
return true;
} | [
"public",
"function",
"validateXml",
"(",
"\\",
"DOMDocument",
"$",
"domDocument",
",",
"$",
"schemaFile",
"=",
"null",
",",
"$",
"failOnErrors",
"=",
"false",
")",
"{",
"// if we got a specific schema file we will use it, otherwise we will use the one we got globally",
"$"... | Will validate a DOM document against a schema file.
Will return true if validation passes, false otherwise.
A specific schema file to use might be passed as well, if none is given the tester tries to choose the right one
@param \DOMDocument $domDocument DOM document to validate
@param string|null $schemaFile The specific schema file to validate against (optional)
@param boolean $failOnErrors If the validation should fail on error (optional)
@return boolean
@throws \AppserverIo\Appserver\Core\Api\InvalidConfigurationException If $failOnErrors is set to true an exception will be thrown on errors | [
"Will",
"validate",
"a",
"DOM",
"document",
"against",
"a",
"schema",
"file",
".",
"Will",
"return",
"true",
"if",
"validation",
"passes",
"false",
"otherwise",
".",
"A",
"specific",
"schema",
"file",
"to",
"use",
"might",
"be",
"passed",
"as",
"well",
"if... | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/ConfigurationService.php#L229-L242 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Scanner/CronJob.php | CronJob.run | public function run()
{
try {
// register shutdown handler
register_shutdown_function(array(&$this, "shutdown"));
// store the actual directory
$actualDir = getcwd();
// load the node data with the command information
$executeNode = $this->jobNode->getExecute();
// try to load the script from the configuration
if ($script = $executeNode->getScript()) {
// change the working directory
if ($execDir = $executeNode->getDirectory()) {
chdir($execDir);
}
// check if the configured script is a file
if (is_file($script) && is_executable($script)) {
// initialize the exec params
$output = array();
$returnVar = 0;
// execute the script on the command line
exec($executeNode, $output, $returnVar);
// restore the old directory
if ($execDir && $actualDir) {
chdir($actualDir);
}
// query whether the script has been executed or not
if ($returnVar !== 0) {
throw new \Exception(implode(PHP_EOL, $output));
} else {
error_log(implode(PHP_EOL, $output));
}
} else {
throw new \Exception(sprintf('Script %s is not a file or not executable', $script));
}
} else {
throw new \Exception(sprintf('Can\t find a script configured in job', $this->jobNode->getName()));
}
} catch (\Exception $e) {
// restore the old directory
chdir($actualDir);
// log the exception
error_log($e->__toString());
}
} | php | public function run()
{
try {
// register shutdown handler
register_shutdown_function(array(&$this, "shutdown"));
// store the actual directory
$actualDir = getcwd();
// load the node data with the command information
$executeNode = $this->jobNode->getExecute();
// try to load the script from the configuration
if ($script = $executeNode->getScript()) {
// change the working directory
if ($execDir = $executeNode->getDirectory()) {
chdir($execDir);
}
// check if the configured script is a file
if (is_file($script) && is_executable($script)) {
// initialize the exec params
$output = array();
$returnVar = 0;
// execute the script on the command line
exec($executeNode, $output, $returnVar);
// restore the old directory
if ($execDir && $actualDir) {
chdir($actualDir);
}
// query whether the script has been executed or not
if ($returnVar !== 0) {
throw new \Exception(implode(PHP_EOL, $output));
} else {
error_log(implode(PHP_EOL, $output));
}
} else {
throw new \Exception(sprintf('Script %s is not a file or not executable', $script));
}
} else {
throw new \Exception(sprintf('Can\t find a script configured in job', $this->jobNode->getName()));
}
} catch (\Exception $e) {
// restore the old directory
chdir($actualDir);
// log the exception
error_log($e->__toString());
}
} | [
"public",
"function",
"run",
"(",
")",
"{",
"try",
"{",
"// register shutdown handler",
"register_shutdown_function",
"(",
"array",
"(",
"&",
"$",
"this",
",",
"\"shutdown\"",
")",
")",
";",
"// store the actual directory",
"$",
"actualDir",
"=",
"getcwd",
"(",
... | Main method that executes the CRON job in a separate thread.
@return void | [
"Main",
"method",
"that",
"executes",
"the",
"CRON",
"job",
"in",
"a",
"separate",
"thread",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Scanner/CronJob.php#L57-L112 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Utilities/PermissionHelper.php | PermissionHelper.sudo | public static function sudo(callable $callable, array $arguments = array())
{
// don't do anything under Windows
if (FileSystem::getOsIdentifier() === FileSystem::OS_IDENTIFIER_WIN) {
return call_user_func_array($callable, $arguments);
}
// get the current user user pair (super user and effective user)
$currentUserId = (integer) posix_geteuid();
$superUserId = (integer) posix_getuid();
// temporarily switch to the super user
posix_seteuid($superUserId);
// execute the callable
$result = call_user_func_array($callable, $arguments);
// switch back to the effective user
posix_seteuid($currentUserId);
return $result;
} | php | public static function sudo(callable $callable, array $arguments = array())
{
// don't do anything under Windows
if (FileSystem::getOsIdentifier() === FileSystem::OS_IDENTIFIER_WIN) {
return call_user_func_array($callable, $arguments);
}
// get the current user user pair (super user and effective user)
$currentUserId = (integer) posix_geteuid();
$superUserId = (integer) posix_getuid();
// temporarily switch to the super user
posix_seteuid($superUserId);
// execute the callable
$result = call_user_func_array($callable, $arguments);
// switch back to the effective user
posix_seteuid($currentUserId);
return $result;
} | [
"public",
"static",
"function",
"sudo",
"(",
"callable",
"$",
"callable",
",",
"array",
"$",
"arguments",
"=",
"array",
"(",
")",
")",
"{",
"// don't do anything under Windows",
"if",
"(",
"FileSystem",
"::",
"getOsIdentifier",
"(",
")",
"===",
"FileSystem",
"... | Helper method which allows to execute a callable as the super user the server got started by.
@param callable $callable The callable to run
@param array $arguments Arguments to pass to the callable
@return mixed The callables result | [
"Helper",
"method",
"which",
"allows",
"to",
"execute",
"a",
"callable",
"as",
"the",
"super",
"user",
"the",
"server",
"got",
"started",
"by",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/PermissionHelper.php#L43-L64 |
appserver-io/appserver | src/AppserverIo/Appserver/MessageQueue/QueueLocator.php | QueueLocator.lookup | public function lookup(QueueContextInterface $queueManager, $lookupName, $sessionId = null, array $args = array())
{
// load registered queues
$queues = $queueManager->getQueues();
// return the requested message queue for the passed priority key, if available
if (isset($queues[$lookupName])) {
return $queues[$lookupName];
}
} | php | public function lookup(QueueContextInterface $queueManager, $lookupName, $sessionId = null, array $args = array())
{
// load registered queues
$queues = $queueManager->getQueues();
// return the requested message queue for the passed priority key, if available
if (isset($queues[$lookupName])) {
return $queues[$lookupName];
}
} | [
"public",
"function",
"lookup",
"(",
"QueueContextInterface",
"$",
"queueManager",
",",
"$",
"lookupName",
",",
"$",
"sessionId",
"=",
"null",
",",
"array",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"// load registered queues",
"$",
"queues",
"=",
"$",
... | Runs a lookup for the message queue with the passed lookup name and
session ID.
@param \AppserverIo\Psr\Pms\QueueContextInterface $queueManager The queue manager instance
@param string $lookupName The queue lookup name
@param string $sessionId The session ID
@param array $args The arguments passed to the queue
@return \AppserverIo\Psr\Pms\QueueInterface The requested queue instance | [
"Runs",
"a",
"lookup",
"for",
"the",
"message",
"queue",
"with",
"the",
"passed",
"lookup",
"name",
"and",
"session",
"ID",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/MessageQueue/QueueLocator.php#L52-L62 |
appserver-io/appserver | src/AppserverIo/Appserver/MessageQueue/QueueLocator.php | QueueLocator.locate | public function locate(QueueContextInterface $queueManager, QueueInterface $queue)
{
// load registered queues and requested queue name
$queues = $queueManager->getQueues();
// return the requested message queue for the passed priority key, if available
if (array_key_exists($queueName = $queue->getName(), $queues)) {
return $queues[$queueName];
}
} | php | public function locate(QueueContextInterface $queueManager, QueueInterface $queue)
{
// load registered queues and requested queue name
$queues = $queueManager->getQueues();
// return the requested message queue for the passed priority key, if available
if (array_key_exists($queueName = $queue->getName(), $queues)) {
return $queues[$queueName];
}
} | [
"public",
"function",
"locate",
"(",
"QueueContextInterface",
"$",
"queueManager",
",",
"QueueInterface",
"$",
"queue",
")",
"{",
"// load registered queues and requested queue name",
"$",
"queues",
"=",
"$",
"queueManager",
"->",
"getQueues",
"(",
")",
";",
"// retur... | Tries to locate the queue that handles the request and returns the instance
if one can be found.
@param \AppserverIo\Psr\Pms\QueueContextInterface $queueManager The queue manager instance
@param \AppserverIo\Psr\Pms\QueueInterface $queue The queue request
@return \AppserverIo\Psr\Pms\QueueInterface The requested queue instance
@see \AppserverIo\Psr\Pms\ResourceLocatorInterface::locate() | [
"Tries",
"to",
"locate",
"the",
"queue",
"that",
"handles",
"the",
"request",
"and",
"returns",
"the",
"instance",
"if",
"one",
"can",
"be",
"found",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/MessageQueue/QueueLocator.php#L74-L84 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Scanner/DeploymentScanner.php | DeploymentScanner.main | public function main()
{
// load the interval we want to scan the directory
$interval = $this->getInterval();
// load the deployment directory
$directory = $this->getDirectory();
// log the configured deployment directory
$this->getSystemLogger()->debug(sprintf('Start watching directory %s', $directory));
// load the deployment flag
$deploymentFlag = $this->getDeploymentFlag();
// wait until the server has been successfully started at least once
while ($this->getLastSuccessfullyDeployment($deploymentFlag) === 0) {
$this->getSystemLogger()->debug(sprintf('%s is waiting for first successful deployment ...', __CLASS__));
sleep($interval);
}
// load the initial hash value of the deployment directory
$oldHash = $this->getDirectoryHash($directory);
// watch the deployment directory
while (true) {
// load the actual hash value for the deployment directory
$newHash = $this->getDirectoryHash($directory);
// log the found directory hash value
$this->getSystemLogger()->debug(sprintf("Comparing directory hash %s (previous) : %s (actual)", $oldHash, $newHash));
// compare the hash values, if not equal restart the appserver
if ($oldHash !== $newHash) {
// log that changes have been found
$this->getSystemLogger()->debug(sprintf('Found changes in directory %s', $directory));
// log the UNIX timestamp of the last successful deployment
$lastSuccessfullDeployment = $this->getLastSuccessfullyDeployment($deploymentFlag);
// restart the appserver
$this->restart();
// wait until deployment has been finished
while ($lastSuccessfullDeployment == $this->getLastSuccessfullyDeployment($deploymentFlag)) {
sleep($interval);
}
// set the directory new hash value after successful deployment
$oldHash = $this->getDirectoryHash($directory);
// log that the appserver has been restarted successful
$this->getSystemLogger()->debug('appserver has successfully been restarted');
} else {
// if no changes has been found, wait a second
sleep($interval);
}
}
} | php | public function main()
{
// load the interval we want to scan the directory
$interval = $this->getInterval();
// load the deployment directory
$directory = $this->getDirectory();
// log the configured deployment directory
$this->getSystemLogger()->debug(sprintf('Start watching directory %s', $directory));
// load the deployment flag
$deploymentFlag = $this->getDeploymentFlag();
// wait until the server has been successfully started at least once
while ($this->getLastSuccessfullyDeployment($deploymentFlag) === 0) {
$this->getSystemLogger()->debug(sprintf('%s is waiting for first successful deployment ...', __CLASS__));
sleep($interval);
}
// load the initial hash value of the deployment directory
$oldHash = $this->getDirectoryHash($directory);
// watch the deployment directory
while (true) {
// load the actual hash value for the deployment directory
$newHash = $this->getDirectoryHash($directory);
// log the found directory hash value
$this->getSystemLogger()->debug(sprintf("Comparing directory hash %s (previous) : %s (actual)", $oldHash, $newHash));
// compare the hash values, if not equal restart the appserver
if ($oldHash !== $newHash) {
// log that changes have been found
$this->getSystemLogger()->debug(sprintf('Found changes in directory %s', $directory));
// log the UNIX timestamp of the last successful deployment
$lastSuccessfullDeployment = $this->getLastSuccessfullyDeployment($deploymentFlag);
// restart the appserver
$this->restart();
// wait until deployment has been finished
while ($lastSuccessfullDeployment == $this->getLastSuccessfullyDeployment($deploymentFlag)) {
sleep($interval);
}
// set the directory new hash value after successful deployment
$oldHash = $this->getDirectoryHash($directory);
// log that the appserver has been restarted successful
$this->getSystemLogger()->debug('appserver has successfully been restarted');
} else {
// if no changes has been found, wait a second
sleep($interval);
}
}
} | [
"public",
"function",
"main",
"(",
")",
"{",
"// load the interval we want to scan the directory",
"$",
"interval",
"=",
"$",
"this",
"->",
"getInterval",
"(",
")",
";",
"// load the deployment directory",
"$",
"directory",
"=",
"$",
"this",
"->",
"getDirectory",
"(... | Start's the deployment scanner that restarts the server
when a PHAR should be deployed or undeployed.
@return void
@see \AppserverIo\Appserver\Core\AbstractThread::main() | [
"Start",
"s",
"the",
"deployment",
"scanner",
"that",
"restarts",
"the",
"server",
"when",
"a",
"PHAR",
"should",
"be",
"deployed",
"or",
"undeployed",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Scanner/DeploymentScanner.php#L135-L194 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/AbstractDaemonThread.php | AbstractDaemonThread.stop | public function stop()
{
// log a message that we're waiting for shutdown
$this->log(LogLevel::INFO, sprintf('Now start to shutdown daemon %s', get_class($this)));
// load the default timeout to wait for daemon shutdown
$shutdownTimeout = $this->getDefaultShutdownTimeout();
// start shutdown process
$this->synchronized(function ($self) {
$self->state = EnumState::get(EnumState::HALT);
}, $this);
do {
// log a message that we're waiting for shutdown
$this->log(LogLevel::INFO, sprintf('Wait for shutdown daemon %s', get_class($this)));
// query whether state key is SHUTDOWN or not
$waitForShutdown = $this->state->notEquals(EnumState::get(EnumState::SHUTDOWN));
// sleep and wait for successfull daemon shutdown
$this->sleep($shutdownTimeout);
} while ($waitForShutdown);
// log a message that we're waiting for shutdown
$this->log(LogLevel::INFO, sprintf('Successfully shutdown daemon %s', get_class($this)));
} | php | public function stop()
{
// log a message that we're waiting for shutdown
$this->log(LogLevel::INFO, sprintf('Now start to shutdown daemon %s', get_class($this)));
// load the default timeout to wait for daemon shutdown
$shutdownTimeout = $this->getDefaultShutdownTimeout();
// start shutdown process
$this->synchronized(function ($self) {
$self->state = EnumState::get(EnumState::HALT);
}, $this);
do {
// log a message that we're waiting for shutdown
$this->log(LogLevel::INFO, sprintf('Wait for shutdown daemon %s', get_class($this)));
// query whether state key is SHUTDOWN or not
$waitForShutdown = $this->state->notEquals(EnumState::get(EnumState::SHUTDOWN));
// sleep and wait for successfull daemon shutdown
$this->sleep($shutdownTimeout);
} while ($waitForShutdown);
// log a message that we're waiting for shutdown
$this->log(LogLevel::INFO, sprintf('Successfully shutdown daemon %s', get_class($this)));
} | [
"public",
"function",
"stop",
"(",
")",
"{",
"// log a message that we're waiting for shutdown",
"$",
"this",
"->",
"log",
"(",
"LogLevel",
"::",
"INFO",
",",
"sprintf",
"(",
"'Now start to shutdown daemon %s'",
",",
"get_class",
"(",
"$",
"this",
")",
")",
")",
... | Stops the daemon and finally invokes the cleanup() method.
@return void | [
"Stops",
"the",
"daemon",
"and",
"finally",
"invokes",
"the",
"cleanup",
"()",
"method",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/AbstractDaemonThread.php#L93-L121 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/AbstractDaemonThread.php | AbstractDaemonThread.run | public function run()
{
try {
// register shutdown handler
register_shutdown_function($this->getDefaultShutdownMethod());
// bootstrap the daemon
$this->bootstrap();
// mark the daemon as successfully shutdown
$this->synchronized(function ($self) {
$self->state = EnumState::get(EnumState::RUNNING);
}, $this);
// keep the daemon running
while ($this->keepRunning()) {
try {
$this->iterate($this->getDefaultTimeout());
} catch (\Exception $e) {
$this->log(LogLevel::ERROR, $e->__toString());
}
}
// clean up the instances and free memory
$this->cleanUp();
// mark the daemon as successfully shutdown
$this->synchronized(function ($self) {
$self->state = EnumState::get(EnumState::SHUTDOWN);
}, $this);
} catch (\Exception $e) {
$this->log(LogLevel::ERROR, $e->__toString());
}
} | php | public function run()
{
try {
// register shutdown handler
register_shutdown_function($this->getDefaultShutdownMethod());
// bootstrap the daemon
$this->bootstrap();
// mark the daemon as successfully shutdown
$this->synchronized(function ($self) {
$self->state = EnumState::get(EnumState::RUNNING);
}, $this);
// keep the daemon running
while ($this->keepRunning()) {
try {
$this->iterate($this->getDefaultTimeout());
} catch (\Exception $e) {
$this->log(LogLevel::ERROR, $e->__toString());
}
}
// clean up the instances and free memory
$this->cleanUp();
// mark the daemon as successfully shutdown
$this->synchronized(function ($self) {
$self->state = EnumState::get(EnumState::SHUTDOWN);
}, $this);
} catch (\Exception $e) {
$this->log(LogLevel::ERROR, $e->__toString());
}
} | [
"public",
"function",
"run",
"(",
")",
"{",
"try",
"{",
"// register shutdown handler",
"register_shutdown_function",
"(",
"$",
"this",
"->",
"getDefaultShutdownMethod",
"(",
")",
")",
";",
"// bootstrap the daemon",
"$",
"this",
"->",
"bootstrap",
"(",
")",
";",
... | The daemon's main run method. It should not be necessary to override,
instead use the main(), iterate() and cleanup() methods to implement
the daemons custom functionality.
@return void
@see \Thread::run() | [
"The",
"daemon",
"s",
"main",
"run",
"method",
".",
"It",
"should",
"not",
"be",
"necessary",
"to",
"override",
"instead",
"use",
"the",
"main",
"()",
"iterate",
"()",
"and",
"cleanup",
"()",
"methods",
"to",
"implement",
"the",
"daemons",
"custom",
"funct... | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/AbstractDaemonThread.php#L165-L200 |
ratchetphp/RFC6455 | src/Messaging/MessageBuffer.php | MessageBuffer.frameCheck | public function frameCheck(FrameInterface $frame) {
if (false !== $frame->getRsv1() ||
false !== $frame->getRsv2() ||
false !== $frame->getRsv3()
) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected an invalid reserve code');
}
if ($this->checkForMask && !$frame->isMasked()) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected an incorrect frame mask');
}
$opcode = $frame->getOpcode();
if ($opcode > 2) {
if ($frame->getPayloadLength() > 125 || !$frame->isFinal()) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected a mismatch between final bit and indicated payload length');
}
switch ($opcode) {
case Frame::OP_CLOSE:
$closeCode = 0;
$bin = $frame->getPayload();
if (empty($bin)) {
return $this->newCloseFrame(Frame::CLOSE_NORMAL);
}
if (strlen($bin) === 1) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected an invalid close code');
}
if (strlen($bin) >= 2) {
list($closeCode) = array_merge(unpack('n*', substr($bin, 0, 2)));
}
$checker = $this->closeFrameChecker;
if (!$checker($closeCode)) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected an invalid close code');
}
if (!$this->checkUtf8(substr($bin, 2))) {
return $this->newCloseFrame(Frame::CLOSE_BAD_PAYLOAD, 'Ratchet detected an invalid UTF-8 payload in the close reason');
}
return $frame;
break;
case Frame::OP_PING:
case Frame::OP_PONG:
break;
default:
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected an invalid OP code');
break;
}
return $frame;
}
if (Frame::OP_CONTINUE === $frame->getOpcode() && 0 === count($this->messageBuffer)) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected the first frame of a message was a continue');
}
if (count($this->messageBuffer) > 0 && Frame::OP_CONTINUE !== $frame->getOpcode()) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected invalid OP code when expecting continue frame');
}
return $frame;
} | php | public function frameCheck(FrameInterface $frame) {
if (false !== $frame->getRsv1() ||
false !== $frame->getRsv2() ||
false !== $frame->getRsv3()
) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected an invalid reserve code');
}
if ($this->checkForMask && !$frame->isMasked()) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected an incorrect frame mask');
}
$opcode = $frame->getOpcode();
if ($opcode > 2) {
if ($frame->getPayloadLength() > 125 || !$frame->isFinal()) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected a mismatch between final bit and indicated payload length');
}
switch ($opcode) {
case Frame::OP_CLOSE:
$closeCode = 0;
$bin = $frame->getPayload();
if (empty($bin)) {
return $this->newCloseFrame(Frame::CLOSE_NORMAL);
}
if (strlen($bin) === 1) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected an invalid close code');
}
if (strlen($bin) >= 2) {
list($closeCode) = array_merge(unpack('n*', substr($bin, 0, 2)));
}
$checker = $this->closeFrameChecker;
if (!$checker($closeCode)) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected an invalid close code');
}
if (!$this->checkUtf8(substr($bin, 2))) {
return $this->newCloseFrame(Frame::CLOSE_BAD_PAYLOAD, 'Ratchet detected an invalid UTF-8 payload in the close reason');
}
return $frame;
break;
case Frame::OP_PING:
case Frame::OP_PONG:
break;
default:
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected an invalid OP code');
break;
}
return $frame;
}
if (Frame::OP_CONTINUE === $frame->getOpcode() && 0 === count($this->messageBuffer)) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected the first frame of a message was a continue');
}
if (count($this->messageBuffer) > 0 && Frame::OP_CONTINUE !== $frame->getOpcode()) {
return $this->newCloseFrame(Frame::CLOSE_PROTOCOL, 'Ratchet detected invalid OP code when expecting continue frame');
}
return $frame;
} | [
"public",
"function",
"frameCheck",
"(",
"FrameInterface",
"$",
"frame",
")",
"{",
"if",
"(",
"false",
"!==",
"$",
"frame",
"->",
"getRsv1",
"(",
")",
"||",
"false",
"!==",
"$",
"frame",
"->",
"getRsv2",
"(",
")",
"||",
"false",
"!==",
"$",
"frame",
... | Check a frame to be added to the current message buffer
@param \Ratchet\RFC6455\Messaging\FrameInterface|FrameInterface $frame
@return \Ratchet\RFC6455\Messaging\FrameInterface|FrameInterface | [
"Check",
"a",
"frame",
"to",
"be",
"added",
"to",
"the",
"current",
"message",
"buffer"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/MessageBuffer.php#L120-L188 |
ratchetphp/RFC6455 | src/Messaging/MessageBuffer.php | MessageBuffer.checkMessage | public function checkMessage(MessageInterface $message) {
if (!$message->isBinary()) {
if (!$this->checkUtf8($message->getPayload())) {
return Frame::CLOSE_BAD_PAYLOAD;
}
}
return true;
} | php | public function checkMessage(MessageInterface $message) {
if (!$message->isBinary()) {
if (!$this->checkUtf8($message->getPayload())) {
return Frame::CLOSE_BAD_PAYLOAD;
}
}
return true;
} | [
"public",
"function",
"checkMessage",
"(",
"MessageInterface",
"$",
"message",
")",
"{",
"if",
"(",
"!",
"$",
"message",
"->",
"isBinary",
"(",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"checkUtf8",
"(",
"$",
"message",
"->",
"getPayload",
"(",... | Determine if a message is valid
@param \Ratchet\RFC6455\Messaging\MessageInterface
@return bool|int true if valid - false if incomplete - int of recommended close code | [
"Determine",
"if",
"a",
"message",
"is",
"valid"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/MessageBuffer.php#L195-L203 |
ratchetphp/RFC6455 | src/Messaging/Frame.php | Frame.isCoalesced | public function isCoalesced() {
if (true === $this->isCoalesced) {
return true;
}
try {
$payload_length = $this->getPayloadLength();
$payload_start = $this->getPayloadStartingByte();
} catch (\UnderflowException $e) {
return false;
}
$this->isCoalesced = $this->bytesRecvd >= $payload_length + $payload_start;
return $this->isCoalesced;
} | php | public function isCoalesced() {
if (true === $this->isCoalesced) {
return true;
}
try {
$payload_length = $this->getPayloadLength();
$payload_start = $this->getPayloadStartingByte();
} catch (\UnderflowException $e) {
return false;
}
$this->isCoalesced = $this->bytesRecvd >= $payload_length + $payload_start;
return $this->isCoalesced;
} | [
"public",
"function",
"isCoalesced",
"(",
")",
"{",
"if",
"(",
"true",
"===",
"$",
"this",
"->",
"isCoalesced",
")",
"{",
"return",
"true",
";",
"}",
"try",
"{",
"$",
"payload_length",
"=",
"$",
"this",
"->",
"getPayloadLength",
"(",
")",
";",
"$",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/Frame.php#L106-L121 |
ratchetphp/RFC6455 | src/Messaging/Frame.php | Frame.addBuffer | public function addBuffer($buf) {
$len = strlen($buf);
$this->data .= $buf;
$this->bytesRecvd += $len;
if ($this->firstByte === -1 && $this->bytesRecvd !== 0) {
$this->firstByte = ord($this->data[0]);
}
if ($this->secondByte === -1 && $this->bytesRecvd >= 2) {
$this->secondByte = ord($this->data[1]);
}
} | php | public function addBuffer($buf) {
$len = strlen($buf);
$this->data .= $buf;
$this->bytesRecvd += $len;
if ($this->firstByte === -1 && $this->bytesRecvd !== 0) {
$this->firstByte = ord($this->data[0]);
}
if ($this->secondByte === -1 && $this->bytesRecvd >= 2) {
$this->secondByte = ord($this->data[1]);
}
} | [
"public",
"function",
"addBuffer",
"(",
"$",
"buf",
")",
"{",
"$",
"len",
"=",
"strlen",
"(",
"$",
"buf",
")",
";",
"$",
"this",
"->",
"data",
".=",
"$",
"buf",
";",
"$",
"this",
"->",
"bytesRecvd",
"+=",
"$",
"len",
";",
"if",
"(",
"$",
"this"... | {@inheritdoc} | [
"{"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/Frame.php#L126-L139 |
ratchetphp/RFC6455 | src/Messaging/Frame.php | Frame.getMaskingKey | public function getMaskingKey() {
if (!$this->isMasked()) {
return '';
}
$start = 1 + $this->getNumPayloadBytes();
if ($this->bytesRecvd < $start + static::MASK_LENGTH) {
throw call_user_func($this->ufeg, 'Not enough data buffered to calculate the masking key');
}
return substr($this->data, $start, static::MASK_LENGTH);
} | php | public function getMaskingKey() {
if (!$this->isMasked()) {
return '';
}
$start = 1 + $this->getNumPayloadBytes();
if ($this->bytesRecvd < $start + static::MASK_LENGTH) {
throw call_user_func($this->ufeg, 'Not enough data buffered to calculate the masking key');
}
return substr($this->data, $start, static::MASK_LENGTH);
} | [
"public",
"function",
"getMaskingKey",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isMasked",
"(",
")",
")",
"{",
"return",
"''",
";",
"}",
"$",
"start",
"=",
"1",
"+",
"$",
"this",
"->",
"getNumPayloadBytes",
"(",
")",
";",
"if",
"(",
"$"... | {@inheritdoc} | [
"{"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/Frame.php#L202-L214 |
ratchetphp/RFC6455 | src/Messaging/Frame.php | Frame.generateMaskingKey | public function generateMaskingKey() {
$mask = '';
for ($i = 1; $i <= static::MASK_LENGTH; $i++) {
$mask .= chr(rand(32, 126));
}
return $mask;
} | php | public function generateMaskingKey() {
$mask = '';
for ($i = 1; $i <= static::MASK_LENGTH; $i++) {
$mask .= chr(rand(32, 126));
}
return $mask;
} | [
"public",
"function",
"generateMaskingKey",
"(",
")",
"{",
"$",
"mask",
"=",
"''",
";",
"for",
"(",
"$",
"i",
"=",
"1",
";",
"$",
"i",
"<=",
"static",
"::",
"MASK_LENGTH",
";",
"$",
"i",
"++",
")",
"{",
"$",
"mask",
".=",
"chr",
"(",
"rand",
"(... | Create a 4 byte masking key
@return string | [
"Create",
"a",
"4",
"byte",
"masking",
"key"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/Frame.php#L220-L228 |
ratchetphp/RFC6455 | src/Messaging/Frame.php | Frame.maskPayload | public function maskPayload($maskingKey = null) {
if (null === $maskingKey) {
$maskingKey = $this->generateMaskingKey();
}
if (static::MASK_LENGTH !== strlen($maskingKey)) {
throw new \InvalidArgumentException("Masking key must be " . static::MASK_LENGTH ." characters");
}
if (extension_loaded('mbstring') && true !== mb_check_encoding($maskingKey, 'US-ASCII')) {
throw new \OutOfBoundsException("Masking key MUST be ASCII");
}
$this->unMaskPayload();
$this->secondByte = $this->secondByte | 128;
$this->data[1] = chr($this->secondByte);
$this->data = substr_replace($this->data, $maskingKey, $this->getNumPayloadBytes() + 1, 0);
$this->bytesRecvd += static::MASK_LENGTH;
$this->data = substr_replace($this->data, $this->applyMask($maskingKey), $this->getPayloadStartingByte(), $this->getPayloadLength());
return $this;
} | php | public function maskPayload($maskingKey = null) {
if (null === $maskingKey) {
$maskingKey = $this->generateMaskingKey();
}
if (static::MASK_LENGTH !== strlen($maskingKey)) {
throw new \InvalidArgumentException("Masking key must be " . static::MASK_LENGTH ." characters");
}
if (extension_loaded('mbstring') && true !== mb_check_encoding($maskingKey, 'US-ASCII')) {
throw new \OutOfBoundsException("Masking key MUST be ASCII");
}
$this->unMaskPayload();
$this->secondByte = $this->secondByte | 128;
$this->data[1] = chr($this->secondByte);
$this->data = substr_replace($this->data, $maskingKey, $this->getNumPayloadBytes() + 1, 0);
$this->bytesRecvd += static::MASK_LENGTH;
$this->data = substr_replace($this->data, $this->applyMask($maskingKey), $this->getPayloadStartingByte(), $this->getPayloadLength());
return $this;
} | [
"public",
"function",
"maskPayload",
"(",
"$",
"maskingKey",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"maskingKey",
")",
"{",
"$",
"maskingKey",
"=",
"$",
"this",
"->",
"generateMaskingKey",
"(",
")",
";",
"}",
"if",
"(",
"static",
"::",
... | Apply a mask to the payload
@param string|null If NULL is passed a masking key will be generated
@throws \OutOfBoundsException
@throws \InvalidArgumentException If there is an issue with the given masking key
@return Frame | [
"Apply",
"a",
"mask",
"to",
"the",
"payload"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/Frame.php#L237-L261 |
ratchetphp/RFC6455 | src/Messaging/Frame.php | Frame.unMaskPayload | public function unMaskPayload() {
if (!$this->isCoalesced()) {
throw call_user_func($this->ufeg, 'Frame must be coalesced before applying mask');
}
if (!$this->isMasked()) {
return $this;
}
$maskingKey = $this->getMaskingKey();
$this->secondByte = $this->secondByte & ~128;
$this->data[1] = chr($this->secondByte);
$this->data = substr_replace($this->data, '', $this->getNumPayloadBytes() + 1, static::MASK_LENGTH);
$this->bytesRecvd -= static::MASK_LENGTH;
$this->data = substr_replace($this->data, $this->applyMask($maskingKey), $this->getPayloadStartingByte(), $this->getPayloadLength());
return $this;
} | php | public function unMaskPayload() {
if (!$this->isCoalesced()) {
throw call_user_func($this->ufeg, 'Frame must be coalesced before applying mask');
}
if (!$this->isMasked()) {
return $this;
}
$maskingKey = $this->getMaskingKey();
$this->secondByte = $this->secondByte & ~128;
$this->data[1] = chr($this->secondByte);
$this->data = substr_replace($this->data, '', $this->getNumPayloadBytes() + 1, static::MASK_LENGTH);
$this->bytesRecvd -= static::MASK_LENGTH;
$this->data = substr_replace($this->data, $this->applyMask($maskingKey), $this->getPayloadStartingByte(), $this->getPayloadLength());
return $this;
} | [
"public",
"function",
"unMaskPayload",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isCoalesced",
"(",
")",
")",
"{",
"throw",
"call_user_func",
"(",
"$",
"this",
"->",
"ufeg",
",",
"'Frame must be coalesced before applying mask'",
")",
";",
"}",
"if",... | Remove a mask from the payload
@throws \UnderFlowException If the frame is not coalesced
@return Frame | [
"Remove",
"a",
"mask",
"from",
"the",
"payload"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/Frame.php#L268-L288 |
ratchetphp/RFC6455 | src/Messaging/Frame.php | Frame.applyMask | public function applyMask($maskingKey, $payload = null) {
if (null === $payload) {
if (!$this->isCoalesced()) {
throw call_user_func($this->ufeg, 'Frame must be coalesced to apply a mask');
}
$payload = substr($this->data, $this->getPayloadStartingByte(), $this->getPayloadLength());
}
$len = strlen($payload);
if (0 === $len) {
return '';
}
return $payload ^ str_pad('', $len, $maskingKey, STR_PAD_RIGHT);
// TODO: Remove this before publish - keeping methods here to compare performance (above is faster but need control against v0.3.3)
$applied = '';
for ($i = 0, $len = strlen($payload); $i < $len; $i++) {
$applied .= $payload[$i] ^ $maskingKey[$i % static::MASK_LENGTH];
}
return $applied;
} | php | public function applyMask($maskingKey, $payload = null) {
if (null === $payload) {
if (!$this->isCoalesced()) {
throw call_user_func($this->ufeg, 'Frame must be coalesced to apply a mask');
}
$payload = substr($this->data, $this->getPayloadStartingByte(), $this->getPayloadLength());
}
$len = strlen($payload);
if (0 === $len) {
return '';
}
return $payload ^ str_pad('', $len, $maskingKey, STR_PAD_RIGHT);
// TODO: Remove this before publish - keeping methods here to compare performance (above is faster but need control against v0.3.3)
$applied = '';
for ($i = 0, $len = strlen($payload); $i < $len; $i++) {
$applied .= $payload[$i] ^ $maskingKey[$i % static::MASK_LENGTH];
}
return $applied;
} | [
"public",
"function",
"applyMask",
"(",
"$",
"maskingKey",
",",
"$",
"payload",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"payload",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isCoalesced",
"(",
")",
")",
"{",
"throw",
"call_user_func"... | Apply a mask to a string or the payload of the instance
@param string $maskingKey The 4 character masking key to be applied
@param string|null $payload A string to mask or null to use the payload
@throws \UnderflowException If using the payload but enough hasn't been buffered
@return string The masked string | [
"Apply",
"a",
"mask",
"to",
"a",
"string",
"or",
"the",
"payload",
"of",
"the",
"instance"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/Frame.php#L297-L322 |
ratchetphp/RFC6455 | src/Messaging/Frame.php | Frame.getPayloadLength | public function getPayloadLength() {
if ($this->defPayLen !== -1) {
return $this->defPayLen;
}
$this->defPayLen = $this->getFirstPayloadVal();
if ($this->defPayLen <= 125) {
return $this->getPayloadLength();
}
$byte_length = $this->getNumPayloadBytes();
if ($this->bytesRecvd < 1 + $byte_length) {
$this->defPayLen = -1;
throw call_user_func($this->ufeg, 'Not enough data buffered to determine payload length');
}
$len = 0;
for ($i = 2; $i <= $byte_length; $i++) {
$len <<= 8;
$len += ord($this->data[$i]);
}
$this->defPayLen = $len;
return $this->getPayloadLength();
} | php | public function getPayloadLength() {
if ($this->defPayLen !== -1) {
return $this->defPayLen;
}
$this->defPayLen = $this->getFirstPayloadVal();
if ($this->defPayLen <= 125) {
return $this->getPayloadLength();
}
$byte_length = $this->getNumPayloadBytes();
if ($this->bytesRecvd < 1 + $byte_length) {
$this->defPayLen = -1;
throw call_user_func($this->ufeg, 'Not enough data buffered to determine payload length');
}
$len = 0;
for ($i = 2; $i <= $byte_length; $i++) {
$len <<= 8;
$len += ord($this->data[$i]);
}
$this->defPayLen = $len;
return $this->getPayloadLength();
} | [
"public",
"function",
"getPayloadLength",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"defPayLen",
"!==",
"-",
"1",
")",
"{",
"return",
"$",
"this",
"->",
"defPayLen",
";",
"}",
"$",
"this",
"->",
"defPayLen",
"=",
"$",
"this",
"->",
"getFirstPayloadV... | {@inheritdoc} | [
"{"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/Frame.php#L389-L414 |
ratchetphp/RFC6455 | src/Messaging/Frame.php | Frame.extractOverflow | public function extractOverflow() {
if ($this->isCoalesced()) {
$endPoint = $this->getPayloadLength();
$endPoint += $this->getPayloadStartingByte();
if ($this->bytesRecvd > $endPoint) {
$overflow = substr($this->data, $endPoint);
$this->data = substr($this->data, 0, $endPoint);
return $overflow;
}
}
return '';
} | php | public function extractOverflow() {
if ($this->isCoalesced()) {
$endPoint = $this->getPayloadLength();
$endPoint += $this->getPayloadStartingByte();
if ($this->bytesRecvd > $endPoint) {
$overflow = substr($this->data, $endPoint);
$this->data = substr($this->data, 0, $endPoint);
return $overflow;
}
}
return '';
} | [
"public",
"function",
"extractOverflow",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isCoalesced",
"(",
")",
")",
"{",
"$",
"endPoint",
"=",
"$",
"this",
"->",
"getPayloadLength",
"(",
")",
";",
"$",
"endPoint",
"+=",
"$",
"this",
"->",
"getPayloadSt... | Sometimes clients will concatenate more than one frame over the wire
This method will take the extra bytes off the end and return them
@return string | [
"Sometimes",
"clients",
"will",
"concatenate",
"more",
"than",
"one",
"frame",
"over",
"the",
"wire",
"This",
"method",
"will",
"take",
"the",
"extra",
"bytes",
"off",
"the",
"end",
"and",
"return",
"them"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/Frame.php#L458-L472 |
ratchetphp/RFC6455 | src/Handshake/ServerNegotiator.php | ServerNegotiator.handshake | public function handshake(RequestInterface $request) {
if (true !== $this->verifier->verifyMethod($request->getMethod())) {
return new Response(405, ['Allow' => 'GET']);
}
if (true !== $this->verifier->verifyHTTPVersion($request->getProtocolVersion())) {
return new Response(505);
}
if (true !== $this->verifier->verifyRequestURI($request->getUri()->getPath())) {
return new Response(400);
}
if (true !== $this->verifier->verifyHost($request->getHeader('Host'))) {
return new Response(400);
}
$upgradeSuggestion = [
'Connection' => 'Upgrade',
'Upgrade' => 'websocket',
'Sec-WebSocket-Version' => $this->getVersionNumber()
];
if (count($this->_supportedSubProtocols) > 0) {
$upgradeSuggestion['Sec-WebSocket-Protocol'] = implode(', ', array_keys($this->_supportedSubProtocols));
}
if (true !== $this->verifier->verifyUpgradeRequest($request->getHeader('Upgrade'))) {
return new Response(426, $upgradeSuggestion, null, '1.1', 'Upgrade header MUST be provided');
}
if (true !== $this->verifier->verifyConnection($request->getHeader('Connection'))) {
return new Response(400, [], null, '1.1', 'Connection Upgrade MUST be requested');
}
if (true !== $this->verifier->verifyKey($request->getHeader('Sec-WebSocket-Key'))) {
return new Response(400, [], null, '1.1', 'Invalid Sec-WebSocket-Key');
}
if (true !== $this->verifier->verifyVersion($request->getHeader('Sec-WebSocket-Version'))) {
return new Response(426, $upgradeSuggestion);
}
$headers = [];
$subProtocols = $request->getHeader('Sec-WebSocket-Protocol');
if (count($subProtocols) > 0 || (count($this->_supportedSubProtocols) > 0 && $this->_strictSubProtocols)) {
$subProtocols = array_map('trim', explode(',', implode(',', $subProtocols)));
$match = array_reduce($subProtocols, function($accumulator, $protocol) {
return $accumulator ?: (isset($this->_supportedSubProtocols[$protocol]) ? $protocol : null);
}, null);
if ($this->_strictSubProtocols && null === $match) {
return new Response(426, $upgradeSuggestion, null, '1.1', 'No Sec-WebSocket-Protocols requested supported');
}
if (null !== $match) {
$headers['Sec-WebSocket-Protocol'] = $match;
}
}
return new Response(101, array_merge($headers, [
'Upgrade' => 'websocket'
, 'Connection' => 'Upgrade'
, 'Sec-WebSocket-Accept' => $this->sign((string)$request->getHeader('Sec-WebSocket-Key')[0])
, 'X-Powered-By' => 'Ratchet'
]));
} | php | public function handshake(RequestInterface $request) {
if (true !== $this->verifier->verifyMethod($request->getMethod())) {
return new Response(405, ['Allow' => 'GET']);
}
if (true !== $this->verifier->verifyHTTPVersion($request->getProtocolVersion())) {
return new Response(505);
}
if (true !== $this->verifier->verifyRequestURI($request->getUri()->getPath())) {
return new Response(400);
}
if (true !== $this->verifier->verifyHost($request->getHeader('Host'))) {
return new Response(400);
}
$upgradeSuggestion = [
'Connection' => 'Upgrade',
'Upgrade' => 'websocket',
'Sec-WebSocket-Version' => $this->getVersionNumber()
];
if (count($this->_supportedSubProtocols) > 0) {
$upgradeSuggestion['Sec-WebSocket-Protocol'] = implode(', ', array_keys($this->_supportedSubProtocols));
}
if (true !== $this->verifier->verifyUpgradeRequest($request->getHeader('Upgrade'))) {
return new Response(426, $upgradeSuggestion, null, '1.1', 'Upgrade header MUST be provided');
}
if (true !== $this->verifier->verifyConnection($request->getHeader('Connection'))) {
return new Response(400, [], null, '1.1', 'Connection Upgrade MUST be requested');
}
if (true !== $this->verifier->verifyKey($request->getHeader('Sec-WebSocket-Key'))) {
return new Response(400, [], null, '1.1', 'Invalid Sec-WebSocket-Key');
}
if (true !== $this->verifier->verifyVersion($request->getHeader('Sec-WebSocket-Version'))) {
return new Response(426, $upgradeSuggestion);
}
$headers = [];
$subProtocols = $request->getHeader('Sec-WebSocket-Protocol');
if (count($subProtocols) > 0 || (count($this->_supportedSubProtocols) > 0 && $this->_strictSubProtocols)) {
$subProtocols = array_map('trim', explode(',', implode(',', $subProtocols)));
$match = array_reduce($subProtocols, function($accumulator, $protocol) {
return $accumulator ?: (isset($this->_supportedSubProtocols[$protocol]) ? $protocol : null);
}, null);
if ($this->_strictSubProtocols && null === $match) {
return new Response(426, $upgradeSuggestion, null, '1.1', 'No Sec-WebSocket-Protocols requested supported');
}
if (null !== $match) {
$headers['Sec-WebSocket-Protocol'] = $match;
}
}
return new Response(101, array_merge($headers, [
'Upgrade' => 'websocket'
, 'Connection' => 'Upgrade'
, 'Sec-WebSocket-Accept' => $this->sign((string)$request->getHeader('Sec-WebSocket-Key')[0])
, 'X-Powered-By' => 'Ratchet'
]));
} | [
"public",
"function",
"handshake",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"if",
"(",
"true",
"!==",
"$",
"this",
"->",
"verifier",
"->",
"verifyMethod",
"(",
"$",
"request",
"->",
"getMethod",
"(",
")",
")",
")",
"{",
"return",
"new",
"Respon... | {@inheritdoc} | [
"{"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Handshake/ServerNegotiator.php#L41-L106 |
ratchetphp/RFC6455 | src/Messaging/Message.php | Message.isCoalesced | public function isCoalesced() {
if (count($this->_frames) == 0) {
return false;
}
$last = $this->_frames->top();
return ($last->isCoalesced() && $last->isFinal());
} | php | public function isCoalesced() {
if (count($this->_frames) == 0) {
return false;
}
$last = $this->_frames->top();
return ($last->isCoalesced() && $last->isFinal());
} | [
"public",
"function",
"isCoalesced",
"(",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"_frames",
")",
"==",
"0",
")",
"{",
"return",
"false",
";",
"}",
"$",
"last",
"=",
"$",
"this",
"->",
"_frames",
"->",
"top",
"(",
")",
";",
"return"... | {@inheritdoc} | [
"{"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/Message.php#L28-L36 |
ratchetphp/RFC6455 | src/Messaging/Message.php | Message.getPayloadLength | public function getPayloadLength() {
$len = 0;
foreach ($this->_frames as $frame) {
try {
$len += $frame->getPayloadLength();
} catch (\UnderflowException $e) {
// Not an error, want the current amount buffered
}
}
return $len;
} | php | public function getPayloadLength() {
$len = 0;
foreach ($this->_frames as $frame) {
try {
$len += $frame->getPayloadLength();
} catch (\UnderflowException $e) {
// Not an error, want the current amount buffered
}
}
return $len;
} | [
"public",
"function",
"getPayloadLength",
"(",
")",
"{",
"$",
"len",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"_frames",
"as",
"$",
"frame",
")",
"{",
"try",
"{",
"$",
"len",
"+=",
"$",
"frame",
"->",
"getPayloadLength",
"(",
")",
";",
"}"... | {@inheritdoc} | [
"{"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/Message.php#L61-L73 |
ratchetphp/RFC6455 | src/Messaging/Message.php | Message.getContents | public function getContents() {
if (!$this->isCoalesced()) {
throw new \UnderflowException("Message has not been put back together yet");
}
$buffer = '';
foreach ($this->_frames as $frame) {
$buffer .= $frame->getContents();
}
return $buffer;
} | php | public function getContents() {
if (!$this->isCoalesced()) {
throw new \UnderflowException("Message has not been put back together yet");
}
$buffer = '';
foreach ($this->_frames as $frame) {
$buffer .= $frame->getContents();
}
return $buffer;
} | [
"public",
"function",
"getContents",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isCoalesced",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"UnderflowException",
"(",
"\"Message has not been put back together yet\"",
")",
";",
"}",
"$",
"buffer",
"=",
"'... | {@inheritdoc} | [
"{"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Messaging/Message.php#L89-L101 |
ratchetphp/RFC6455 | src/Handshake/RequestVerifier.php | RequestVerifier.verifyAll | public function verifyAll(RequestInterface $request) {
$passes = 0;
$passes += (int)$this->verifyMethod($request->getMethod());
$passes += (int)$this->verifyHTTPVersion($request->getProtocolVersion());
$passes += (int)$this->verifyRequestURI($request->getUri()->getPath());
$passes += (int)$this->verifyHost($request->getHeader('Host'));
$passes += (int)$this->verifyUpgradeRequest($request->getHeader('Upgrade'));
$passes += (int)$this->verifyConnection($request->getHeader('Connection'));
$passes += (int)$this->verifyKey($request->getHeader('Sec-WebSocket-Key'));
$passes += (int)$this->verifyVersion($request->getHeader('Sec-WebSocket-Version'));
return (8 === $passes);
} | php | public function verifyAll(RequestInterface $request) {
$passes = 0;
$passes += (int)$this->verifyMethod($request->getMethod());
$passes += (int)$this->verifyHTTPVersion($request->getProtocolVersion());
$passes += (int)$this->verifyRequestURI($request->getUri()->getPath());
$passes += (int)$this->verifyHost($request->getHeader('Host'));
$passes += (int)$this->verifyUpgradeRequest($request->getHeader('Upgrade'));
$passes += (int)$this->verifyConnection($request->getHeader('Connection'));
$passes += (int)$this->verifyKey($request->getHeader('Sec-WebSocket-Key'));
$passes += (int)$this->verifyVersion($request->getHeader('Sec-WebSocket-Version'));
return (8 === $passes);
} | [
"public",
"function",
"verifyAll",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"$",
"passes",
"=",
"0",
";",
"$",
"passes",
"+=",
"(",
"int",
")",
"$",
"this",
"->",
"verifyMethod",
"(",
"$",
"request",
"->",
"getMethod",
"(",
")",
")",
";",
"... | Given an array of the headers this method will run through all verification methods
@param RequestInterface $request
@return bool TRUE if all headers are valid, FALSE if 1 or more were invalid | [
"Given",
"an",
"array",
"of",
"the",
"headers",
"this",
"method",
"will",
"run",
"through",
"all",
"verification",
"methods"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Handshake/RequestVerifier.php#L18-L31 |
ratchetphp/RFC6455 | src/Handshake/RequestVerifier.php | RequestVerifier.verifyConnection | public function verifyConnection(array $connectionHeader) {
foreach ($connectionHeader as $l) {
$upgrades = array_filter(
array_map('trim', array_map('strtolower', explode(',', $l))),
function ($x) {
return 'upgrade' === $x;
}
);
if (count($upgrades) > 0) {
return true;
}
}
return false;
} | php | public function verifyConnection(array $connectionHeader) {
foreach ($connectionHeader as $l) {
$upgrades = array_filter(
array_map('trim', array_map('strtolower', explode(',', $l))),
function ($x) {
return 'upgrade' === $x;
}
);
if (count($upgrades) > 0) {
return true;
}
}
return false;
} | [
"public",
"function",
"verifyConnection",
"(",
"array",
"$",
"connectionHeader",
")",
"{",
"foreach",
"(",
"$",
"connectionHeader",
"as",
"$",
"l",
")",
"{",
"$",
"upgrades",
"=",
"array_filter",
"(",
"array_map",
"(",
"'trim'",
",",
"array_map",
"(",
"'strt... | Verify the Connection header
@param array $connectionHeader MUST include "Upgrade"
@return bool | [
"Verify",
"the",
"Connection",
"header"
] | train | https://github.com/ratchetphp/RFC6455/blob/9eae01044a82b29fecaf4c539f4e10efe1ac4e14/src/Handshake/RequestVerifier.php#L94-L107 |
hamburgscleanest/guzzle-advanced-throttle | src/RequestLimitGroup.php | RequestLimitGroup.canRequest | public function canRequest(RequestInterface $request, array $options = []) : bool
{
$groupCanRequest = true;
$this->_requestLimiters->rewind();
while ($this->_requestLimiters->valid())
{
/** @var RequestLimiter $requestLimiter */
$requestLimiter = $this->_requestLimiters->current();
$canRequest = $requestLimiter->canRequest($request, $options);
if ($groupCanRequest && !$canRequest)
{
$groupCanRequest = false;
$this->_retryAfter = $requestLimiter->getRemainingSeconds();
}
$this->_requestLimiters->next();
}
return $groupCanRequest;
} | php | public function canRequest(RequestInterface $request, array $options = []) : bool
{
$groupCanRequest = true;
$this->_requestLimiters->rewind();
while ($this->_requestLimiters->valid())
{
/** @var RequestLimiter $requestLimiter */
$requestLimiter = $this->_requestLimiters->current();
$canRequest = $requestLimiter->canRequest($request, $options);
if ($groupCanRequest && !$canRequest)
{
$groupCanRequest = false;
$this->_retryAfter = $requestLimiter->getRemainingSeconds();
}
$this->_requestLimiters->next();
}
return $groupCanRequest;
} | [
"public",
"function",
"canRequest",
"(",
"RequestInterface",
"$",
"request",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"bool",
"{",
"$",
"groupCanRequest",
"=",
"true",
";",
"$",
"this",
"->",
"_requestLimiters",
"->",
"rewind",
"(",
")",
";... | We have to cycle through all the limiters (no early return).
The timers of each limiter have to be updated despite of another limiter already preventing the request.
@param RequestInterface $request
@param array $options
@return bool
@throws \Exception | [
"We",
"have",
"to",
"cycle",
"through",
"all",
"the",
"limiters",
"(",
"no",
"early",
"return",
")",
".",
"The",
"timers",
"of",
"each",
"limiter",
"have",
"to",
"be",
"updated",
"despite",
"of",
"another",
"limiter",
"already",
"preventing",
"the",
"reque... | train | https://github.com/hamburgscleanest/guzzle-advanced-throttle/blob/21e1a9ea4cd39df295444d1fbb180253695852cd/src/RequestLimitGroup.php#L55-L75 |
hamburgscleanest/guzzle-advanced-throttle | src/RequestLimitRuleset.php | RequestLimitRuleset._setStorageAdapter | private function _setStorageAdapter(string $adapterName) : void
{
$adapterClassName = self::STORAGE_MAP[$adapterName] ?? $adapterName;
if (!InterfaceHelper::implementsInterface($adapterClassName, StorageInterface::class))
{
throw new UnknownStorageAdapterException($adapterClassName, \array_values(self::STORAGE_MAP));
}
$this->_storage = new $adapterClassName($this->_config);
} | php | private function _setStorageAdapter(string $adapterName) : void
{
$adapterClassName = self::STORAGE_MAP[$adapterName] ?? $adapterName;
if (!InterfaceHelper::implementsInterface($adapterClassName, StorageInterface::class))
{
throw new UnknownStorageAdapterException($adapterClassName, \array_values(self::STORAGE_MAP));
}
$this->_storage = new $adapterClassName($this->_config);
} | [
"private",
"function",
"_setStorageAdapter",
"(",
"string",
"$",
"adapterName",
")",
":",
"void",
"{",
"$",
"adapterClassName",
"=",
"self",
"::",
"STORAGE_MAP",
"[",
"$",
"adapterName",
"]",
"??",
"$",
"adapterName",
";",
"if",
"(",
"!",
"InterfaceHelper",
... | Sets internal storage adapter for this rule set.
@param string $adapterName
@throws \hamburgscleanest\GuzzleAdvancedThrottle\Exceptions\UnknownStorageAdapterException | [
"Sets",
"internal",
"storage",
"adapter",
"for",
"this",
"rule",
"set",
"."
] | train | https://github.com/hamburgscleanest/guzzle-advanced-throttle/blob/21e1a9ea4cd39df295444d1fbb180253695852cd/src/RequestLimitRuleset.php#L74-L84 |
hamburgscleanest/guzzle-advanced-throttle | src/RequestLimitRuleset.php | RequestLimitRuleset._setCacheStrategy | private function _setCacheStrategy(string $cacheStrategy) : void
{
$cacheStrategyClassName = self::CACHE_STRATEGIES[$cacheStrategy] ?? $cacheStrategy;
if (!InterfaceHelper::implementsInterface($cacheStrategyClassName, CacheStrategy::class))
{
throw new UnknownCacheStrategyException($cacheStrategyClassName, \array_values(self::CACHE_STRATEGIES));
}
$this->_cacheStrategy = new $cacheStrategyClassName($this->_storage);
} | php | private function _setCacheStrategy(string $cacheStrategy) : void
{
$cacheStrategyClassName = self::CACHE_STRATEGIES[$cacheStrategy] ?? $cacheStrategy;
if (!InterfaceHelper::implementsInterface($cacheStrategyClassName, CacheStrategy::class))
{
throw new UnknownCacheStrategyException($cacheStrategyClassName, \array_values(self::CACHE_STRATEGIES));
}
$this->_cacheStrategy = new $cacheStrategyClassName($this->_storage);
} | [
"private",
"function",
"_setCacheStrategy",
"(",
"string",
"$",
"cacheStrategy",
")",
":",
"void",
"{",
"$",
"cacheStrategyClassName",
"=",
"self",
"::",
"CACHE_STRATEGIES",
"[",
"$",
"cacheStrategy",
"]",
"??",
"$",
"cacheStrategy",
";",
"if",
"(",
"!",
"Inte... | Sets the caching strategy for this rule set.
@param string $cacheStrategy
@throws \hamburgscleanest\GuzzleAdvancedThrottle\Exceptions\UnknownCacheStrategyException | [
"Sets",
"the",
"caching",
"strategy",
"for",
"this",
"rule",
"set",
"."
] | train | https://github.com/hamburgscleanest/guzzle-advanced-throttle/blob/21e1a9ea4cd39df295444d1fbb180253695852cd/src/RequestLimitRuleset.php#L91-L101 |
hamburgscleanest/guzzle-advanced-throttle | src/RequestLimiter.php | RequestLimiter._save | private function _save() : void
{
$this->_storage->save(
$this->_host,
$this->_storageKey,
$this->_requestCount,
$this->_timekeeper->getExpiration(),
$this->getRemainingSeconds()
);
} | php | private function _save() : void
{
$this->_storage->save(
$this->_host,
$this->_storageKey,
$this->_requestCount,
$this->_timekeeper->getExpiration(),
$this->getRemainingSeconds()
);
} | [
"private",
"function",
"_save",
"(",
")",
":",
"void",
"{",
"$",
"this",
"->",
"_storage",
"->",
"save",
"(",
"$",
"this",
"->",
"_host",
",",
"$",
"this",
"->",
"_storageKey",
",",
"$",
"this",
"->",
"_requestCount",
",",
"$",
"this",
"->",
"_timeke... | Save timer in storage | [
"Save",
"timer",
"in",
"storage"
] | train | https://github.com/hamburgscleanest/guzzle-advanced-throttle/blob/21e1a9ea4cd39df295444d1fbb180253695852cd/src/RequestLimiter.php#L176-L185 |
hamburgscleanest/guzzle-advanced-throttle | src/Helpers/InterfaceHelper.php | InterfaceHelper.getImplementations | public static function getImplementations(string $interfaceName) : array
{
return \array_filter(\get_declared_classes(), function($className) use ($interfaceName)
{
return self::implementsInterface($className, $interfaceName);
});
} | php | public static function getImplementations(string $interfaceName) : array
{
return \array_filter(\get_declared_classes(), function($className) use ($interfaceName)
{
return self::implementsInterface($className, $interfaceName);
});
} | [
"public",
"static",
"function",
"getImplementations",
"(",
"string",
"$",
"interfaceName",
")",
":",
"array",
"{",
"return",
"\\",
"array_filter",
"(",
"\\",
"get_declared_classes",
"(",
")",
",",
"function",
"(",
"$",
"className",
")",
"use",
"(",
"$",
"int... | Get every class that implements $interfaceName
@param string $interfaceName
@return array | [
"Get",
"every",
"class",
"that",
"implements",
"$interfaceName"
] | train | https://github.com/hamburgscleanest/guzzle-advanced-throttle/blob/21e1a9ea4cd39df295444d1fbb180253695852cd/src/Helpers/InterfaceHelper.php#L18-L24 |
hamburgscleanest/guzzle-advanced-throttle | src/Helpers/InterfaceHelper.php | InterfaceHelper.implementsInterface | public static function implementsInterface(string $implementerClassName, string $interfaceName) : bool
{
return \in_array($interfaceName, \class_implements($implementerClassName), true);
} | php | public static function implementsInterface(string $implementerClassName, string $interfaceName) : bool
{
return \in_array($interfaceName, \class_implements($implementerClassName), true);
} | [
"public",
"static",
"function",
"implementsInterface",
"(",
"string",
"$",
"implementerClassName",
",",
"string",
"$",
"interfaceName",
")",
":",
"bool",
"{",
"return",
"\\",
"in_array",
"(",
"$",
"interfaceName",
",",
"\\",
"class_implements",
"(",
"$",
"implem... | Returns true|false if the $implementerClassName implements interface $interfaceName
@param string $implementerClassName class name of the implementation class to test
@param string $interfaceName name of the interface that should be implemented
@return bool TRUE if the $implementerClassName implements $interfaceName, FALSE otherwise | [
"Returns",
"true|false",
"if",
"the",
"$implementerClassName",
"implements",
"interface",
"$interfaceName"
] | train | https://github.com/hamburgscleanest/guzzle-advanced-throttle/blob/21e1a9ea4cd39df295444d1fbb180253695852cd/src/Helpers/InterfaceHelper.php#L33-L36 |
brick/math | src/BigRational.php | BigRational.nd | public static function nd($numerator, $denominator) : BigRational
{
$numerator = BigInteger::of($numerator);
$denominator = BigInteger::of($denominator);
return new BigRational($numerator, $denominator, true);
} | php | public static function nd($numerator, $denominator) : BigRational
{
$numerator = BigInteger::of($numerator);
$denominator = BigInteger::of($denominator);
return new BigRational($numerator, $denominator, true);
} | [
"public",
"static",
"function",
"nd",
"(",
"$",
"numerator",
",",
"$",
"denominator",
")",
":",
"BigRational",
"{",
"$",
"numerator",
"=",
"BigInteger",
"::",
"of",
"(",
"$",
"numerator",
")",
";",
"$",
"denominator",
"=",
"BigInteger",
"::",
"of",
"(",
... | Creates a BigRational out of a numerator and a denominator.
If the denominator is negative, the signs of both the numerator and the denominator
will be inverted to ensure that the denominator is always positive.
@param BigNumber|number|string $numerator The numerator. Must be convertible to a BigInteger.
@param BigNumber|number|string $denominator The denominator. Must be convertible to a BigInteger.
@return BigRational
@throws NumberFormatException If an argument does not represent a valid number.
@throws RoundingNecessaryException If an argument represents a non-integer number.
@throws DivisionByZeroException If the denominator is zero. | [
"Creates",
"a",
"BigRational",
"out",
"of",
"a",
"numerator",
"and",
"a",
"denominator",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigRational.php#L88-L94 |
brick/math | src/BigRational.php | BigRational.zero | public static function zero() : BigRational
{
static $zero;
if ($zero === null) {
$zero = new BigRational(BigInteger::zero(), BigInteger::one(), false);
}
return $zero;
} | php | public static function zero() : BigRational
{
static $zero;
if ($zero === null) {
$zero = new BigRational(BigInteger::zero(), BigInteger::one(), false);
}
return $zero;
} | [
"public",
"static",
"function",
"zero",
"(",
")",
":",
"BigRational",
"{",
"static",
"$",
"zero",
";",
"if",
"(",
"$",
"zero",
"===",
"null",
")",
"{",
"$",
"zero",
"=",
"new",
"BigRational",
"(",
"BigInteger",
"::",
"zero",
"(",
")",
",",
"BigIntege... | Returns a BigRational representing zero.
@return BigRational | [
"Returns",
"a",
"BigRational",
"representing",
"zero",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigRational.php#L101-L110 |
brick/math | src/BigRational.php | BigRational.one | public static function one() : BigRational
{
static $one;
if ($one === null) {
$one = new BigRational(BigInteger::one(), BigInteger::one(), false);
}
return $one;
} | php | public static function one() : BigRational
{
static $one;
if ($one === null) {
$one = new BigRational(BigInteger::one(), BigInteger::one(), false);
}
return $one;
} | [
"public",
"static",
"function",
"one",
"(",
")",
":",
"BigRational",
"{",
"static",
"$",
"one",
";",
"if",
"(",
"$",
"one",
"===",
"null",
")",
"{",
"$",
"one",
"=",
"new",
"BigRational",
"(",
"BigInteger",
"::",
"one",
"(",
")",
",",
"BigInteger",
... | Returns a BigRational representing one.
@return BigRational | [
"Returns",
"a",
"BigRational",
"representing",
"one",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigRational.php#L117-L126 |
brick/math | src/BigRational.php | BigRational.ten | public static function ten() : BigRational
{
static $ten;
if ($ten === null) {
$ten = new BigRational(BigInteger::ten(), BigInteger::one(), false);
}
return $ten;
} | php | public static function ten() : BigRational
{
static $ten;
if ($ten === null) {
$ten = new BigRational(BigInteger::ten(), BigInteger::one(), false);
}
return $ten;
} | [
"public",
"static",
"function",
"ten",
"(",
")",
":",
"BigRational",
"{",
"static",
"$",
"ten",
";",
"if",
"(",
"$",
"ten",
"===",
"null",
")",
"{",
"$",
"ten",
"=",
"new",
"BigRational",
"(",
"BigInteger",
"::",
"ten",
"(",
")",
",",
"BigInteger",
... | Returns a BigRational representing ten.
@return BigRational | [
"Returns",
"a",
"BigRational",
"representing",
"ten",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigRational.php#L133-L142 |
brick/math | src/BigRational.php | BigRational.plus | public function plus($that) : BigRational
{
$that = BigRational::of($that);
$numerator = $this->numerator->multipliedBy($that->denominator);
$numerator = $numerator->plus($that->numerator->multipliedBy($this->denominator));
$denominator = $this->denominator->multipliedBy($that->denominator);
return new BigRational($numerator, $denominator, false);
} | php | public function plus($that) : BigRational
{
$that = BigRational::of($that);
$numerator = $this->numerator->multipliedBy($that->denominator);
$numerator = $numerator->plus($that->numerator->multipliedBy($this->denominator));
$denominator = $this->denominator->multipliedBy($that->denominator);
return new BigRational($numerator, $denominator, false);
} | [
"public",
"function",
"plus",
"(",
"$",
"that",
")",
":",
"BigRational",
"{",
"$",
"that",
"=",
"BigRational",
"::",
"of",
"(",
"$",
"that",
")",
";",
"$",
"numerator",
"=",
"$",
"this",
"->",
"numerator",
"->",
"multipliedBy",
"(",
"$",
"that",
"->"... | Returns the sum of this number and the given one.
@param BigNumber|number|string $that The number to add.
@return BigRational The result.
@throws MathException If the number is not valid. | [
"Returns",
"the",
"sum",
"of",
"this",
"number",
"and",
"the",
"given",
"one",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigRational.php#L199-L208 |
brick/math | src/BigRational.php | BigRational.dividedBy | public function dividedBy($that) : BigRational
{
$that = BigRational::of($that);
$numerator = $this->numerator->multipliedBy($that->denominator);
$denominator = $this->denominator->multipliedBy($that->numerator);
return new BigRational($numerator, $denominator, true);
} | php | public function dividedBy($that) : BigRational
{
$that = BigRational::of($that);
$numerator = $this->numerator->multipliedBy($that->denominator);
$denominator = $this->denominator->multipliedBy($that->numerator);
return new BigRational($numerator, $denominator, true);
} | [
"public",
"function",
"dividedBy",
"(",
"$",
"that",
")",
":",
"BigRational",
"{",
"$",
"that",
"=",
"BigRational",
"::",
"of",
"(",
"$",
"that",
")",
";",
"$",
"numerator",
"=",
"$",
"this",
"->",
"numerator",
"->",
"multipliedBy",
"(",
"$",
"that",
... | Returns the result of the division of this number by the given one.
@param BigNumber|number|string $that The divisor.
@return BigRational The result.
@throws MathException If the divisor is not a valid number, or is zero. | [
"Returns",
"the",
"result",
"of",
"the",
"division",
"of",
"this",
"number",
"by",
"the",
"given",
"one",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigRational.php#L258-L266 |
brick/math | src/BigRational.php | BigRational.power | public function power(int $exponent) : BigRational
{
if ($exponent === 0) {
$one = BigInteger::one();
return new BigRational($one, $one, false);
}
if ($exponent === 1) {
return $this;
}
return new BigRational(
$this->numerator->power($exponent),
$this->denominator->power($exponent),
false
);
} | php | public function power(int $exponent) : BigRational
{
if ($exponent === 0) {
$one = BigInteger::one();
return new BigRational($one, $one, false);
}
if ($exponent === 1) {
return $this;
}
return new BigRational(
$this->numerator->power($exponent),
$this->denominator->power($exponent),
false
);
} | [
"public",
"function",
"power",
"(",
"int",
"$",
"exponent",
")",
":",
"BigRational",
"{",
"if",
"(",
"$",
"exponent",
"===",
"0",
")",
"{",
"$",
"one",
"=",
"BigInteger",
"::",
"one",
"(",
")",
";",
"return",
"new",
"BigRational",
"(",
"$",
"one",
... | Returns this number exponentiated to the given value.
@param int $exponent The exponent.
@return BigRational The result.
@throws \InvalidArgumentException If the exponent is not in the range 0 to 1,000,000. | [
"Returns",
"this",
"number",
"exponentiated",
"to",
"the",
"given",
"value",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigRational.php#L277-L294 |
brick/math | src/BigRational.php | BigRational.simplified | public function simplified() : BigRational
{
$gcd = $this->numerator->gcd($this->denominator);
$numerator = $this->numerator->quotient($gcd);
$denominator = $this->denominator->quotient($gcd);
return new BigRational($numerator, $denominator, false);
} | php | public function simplified() : BigRational
{
$gcd = $this->numerator->gcd($this->denominator);
$numerator = $this->numerator->quotient($gcd);
$denominator = $this->denominator->quotient($gcd);
return new BigRational($numerator, $denominator, false);
} | [
"public",
"function",
"simplified",
"(",
")",
":",
"BigRational",
"{",
"$",
"gcd",
"=",
"$",
"this",
"->",
"numerator",
"->",
"gcd",
"(",
"$",
"this",
"->",
"denominator",
")",
";",
"$",
"numerator",
"=",
"$",
"this",
"->",
"numerator",
"->",
"quotient... | Returns the simplified value of this BigRational.
@return BigRational | [
"Returns",
"the",
"simplified",
"value",
"of",
"this",
"BigRational",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigRational.php#L335-L343 |
brick/math | src/BigRational.php | BigRational.toBigInteger | public function toBigInteger() : BigInteger
{
$simplified = $this->simplified();
if (! $simplified->denominator->isEqualTo(1)) {
throw new RoundingNecessaryException('This rational number cannot be represented as an integer value without rounding.');
}
return $simplified->numerator;
} | php | public function toBigInteger() : BigInteger
{
$simplified = $this->simplified();
if (! $simplified->denominator->isEqualTo(1)) {
throw new RoundingNecessaryException('This rational number cannot be represented as an integer value without rounding.');
}
return $simplified->numerator;
} | [
"public",
"function",
"toBigInteger",
"(",
")",
":",
"BigInteger",
"{",
"$",
"simplified",
"=",
"$",
"this",
"->",
"simplified",
"(",
")",
";",
"if",
"(",
"!",
"$",
"simplified",
"->",
"denominator",
"->",
"isEqualTo",
"(",
"1",
")",
")",
"{",
"throw",... | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigRational.php#L364-L373 |
brick/math | src/BigRational.php | BigRational.toScale | public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal
{
return $this->numerator->toBigDecimal()->dividedBy($this->denominator, $scale, $roundingMode);
} | php | public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal
{
return $this->numerator->toBigDecimal()->dividedBy($this->denominator, $scale, $roundingMode);
} | [
"public",
"function",
"toScale",
"(",
"int",
"$",
"scale",
",",
"int",
"$",
"roundingMode",
"=",
"RoundingMode",
"::",
"UNNECESSARY",
")",
":",
"BigDecimal",
"{",
"return",
"$",
"this",
"->",
"numerator",
"->",
"toBigDecimal",
"(",
")",
"->",
"dividedBy",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigRational.php#L394-L397 |
brick/math | src/BigRational.php | BigRational.unserialize | public function unserialize($value) : void
{
if (isset($this->numerator)) {
throw new \LogicException('unserialize() is an internal function, it must not be called directly.');
}
[$numerator, $denominator] = \explode('/', $value);
$this->numerator = BigInteger::of($numerator);
$this->denominator = BigInteger::of($denominator);
} | php | public function unserialize($value) : void
{
if (isset($this->numerator)) {
throw new \LogicException('unserialize() is an internal function, it must not be called directly.');
}
[$numerator, $denominator] = \explode('/', $value);
$this->numerator = BigInteger::of($numerator);
$this->denominator = BigInteger::of($denominator);
} | [
"public",
"function",
"unserialize",
"(",
"$",
"value",
")",
":",
"void",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"numerator",
")",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'unserialize() is an internal function, it must not be called direc... | This method is only here to implement interface Serializable and cannot be accessed directly.
@internal
@param string $value
@return void
@throws \LogicException | [
"This",
"method",
"is",
"only",
"here",
"to",
"implement",
"interface",
"Serializable",
"and",
"cannot",
"be",
"accessed",
"directly",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigRational.php#L453-L463 |
brick/math | src/BigNumber.php | BigNumber.of | public static function of($value) : BigNumber
{
if ($value instanceof BigNumber) {
return $value;
}
if (\is_int($value)) {
return new BigInteger((string) $value);
}
if (is_float($value)) {
$value = self::floatToString($value);
} else {
$value = (string) $value;
}
if (\preg_match(self::PARSE_REGEXP, $value, $matches) !== 1) {
throw new NumberFormatException(\sprintf('The given value "%s" does not represent a valid number.', $value));
}
if (isset($matches['denominator'])) {
$numerator = self::cleanUp($matches['integral']);
$denominator = \ltrim($matches['denominator'], '0');
if ($denominator === '') {
throw DivisionByZeroException::denominatorMustNotBeZero();
}
return new BigRational(new BigInteger($numerator), new BigInteger($denominator), false);
}
if (isset($matches['fractional']) || isset($matches['exponent'])) {
$fractional = isset($matches['fractional']) ? $matches['fractional'] : '';
$exponent = isset($matches['exponent']) ? (int) $matches['exponent'] : 0;
$unscaledValue = self::cleanUp($matches['integral'] . $fractional);
$scale = \strlen($fractional) - $exponent;
if ($scale < 0) {
if ($unscaledValue !== '0') {
$unscaledValue .= \str_repeat('0', - $scale);
}
$scale = 0;
}
return new BigDecimal($unscaledValue, $scale);
}
$integral = self::cleanUp($matches['integral']);
return new BigInteger($integral);
} | php | public static function of($value) : BigNumber
{
if ($value instanceof BigNumber) {
return $value;
}
if (\is_int($value)) {
return new BigInteger((string) $value);
}
if (is_float($value)) {
$value = self::floatToString($value);
} else {
$value = (string) $value;
}
if (\preg_match(self::PARSE_REGEXP, $value, $matches) !== 1) {
throw new NumberFormatException(\sprintf('The given value "%s" does not represent a valid number.', $value));
}
if (isset($matches['denominator'])) {
$numerator = self::cleanUp($matches['integral']);
$denominator = \ltrim($matches['denominator'], '0');
if ($denominator === '') {
throw DivisionByZeroException::denominatorMustNotBeZero();
}
return new BigRational(new BigInteger($numerator), new BigInteger($denominator), false);
}
if (isset($matches['fractional']) || isset($matches['exponent'])) {
$fractional = isset($matches['fractional']) ? $matches['fractional'] : '';
$exponent = isset($matches['exponent']) ? (int) $matches['exponent'] : 0;
$unscaledValue = self::cleanUp($matches['integral'] . $fractional);
$scale = \strlen($fractional) - $exponent;
if ($scale < 0) {
if ($unscaledValue !== '0') {
$unscaledValue .= \str_repeat('0', - $scale);
}
$scale = 0;
}
return new BigDecimal($unscaledValue, $scale);
}
$integral = self::cleanUp($matches['integral']);
return new BigInteger($integral);
} | [
"public",
"static",
"function",
"of",
"(",
"$",
"value",
")",
":",
"BigNumber",
"{",
"if",
"(",
"$",
"value",
"instanceof",
"BigNumber",
")",
"{",
"return",
"$",
"value",
";",
"}",
"if",
"(",
"\\",
"is_int",
"(",
"$",
"value",
")",
")",
"{",
"retur... | Creates a BigNumber of the given value.
The concrete return type is dependent on the given value, with the following rules:
- BigNumber instances are returned as is
- integer numbers are returned as BigInteger
- floating point numbers are converted to a string then parsed as such
- strings containing a `/` character are returned as BigRational
- strings containing a `.` character or using an exponential notation are returned as BigDecimal
- strings containing only digits with an optional leading `+` or `-` sign are returned as BigInteger
@param BigNumber|number|string $value
@return BigNumber
@throws NumberFormatException If the format of the number is not valid.
@throws DivisionByZeroException If the value represents a rational number with a denominator of zero. | [
"Creates",
"a",
"BigNumber",
"of",
"the",
"given",
"value",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigNumber.php#L54-L106 |
brick/math | src/BigNumber.php | BigNumber.floatToString | private static function floatToString(float $float) : string
{
$currentLocale = \setlocale(LC_NUMERIC, '0');
\setlocale(LC_NUMERIC, 'C');
$result = (string) $float;
\setlocale(LC_NUMERIC, $currentLocale);
return $result;
} | php | private static function floatToString(float $float) : string
{
$currentLocale = \setlocale(LC_NUMERIC, '0');
\setlocale(LC_NUMERIC, 'C');
$result = (string) $float;
\setlocale(LC_NUMERIC, $currentLocale);
return $result;
} | [
"private",
"static",
"function",
"floatToString",
"(",
"float",
"$",
"float",
")",
":",
"string",
"{",
"$",
"currentLocale",
"=",
"\\",
"setlocale",
"(",
"LC_NUMERIC",
",",
"'0'",
")",
";",
"\\",
"setlocale",
"(",
"LC_NUMERIC",
",",
"'C'",
")",
";",
"$",... | Safely converts float to string, avoiding locale-dependent issues.
@see https://github.com/brick/math/pull/20
@param float $float
@return string | [
"Safely",
"converts",
"float",
"to",
"string",
"avoiding",
"locale",
"-",
"dependent",
"issues",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigNumber.php#L117-L127 |
brick/math | src/BigNumber.php | BigNumber.min | public static function min(...$values) : BigNumber
{
$min = null;
foreach ($values as $value) {
$value = static::of($value);
if ($min === null || $value->isLessThan($min)) {
$min = $value;
}
}
if ($min === null) {
throw new \InvalidArgumentException(__METHOD__ . '() expects at least one value.');
}
return $min;
} | php | public static function min(...$values) : BigNumber
{
$min = null;
foreach ($values as $value) {
$value = static::of($value);
if ($min === null || $value->isLessThan($min)) {
$min = $value;
}
}
if ($min === null) {
throw new \InvalidArgumentException(__METHOD__ . '() expects at least one value.');
}
return $min;
} | [
"public",
"static",
"function",
"min",
"(",
"...",
"$",
"values",
")",
":",
"BigNumber",
"{",
"$",
"min",
"=",
"null",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"static",
"::",
"of",
"(",
"$",
"value",
"... | Returns the minimum of the given values.
@param BigNumber|number|string ...$values The numbers to compare. All the numbers need to be convertible
to an instance of the class this method is called on.
@return static The minimum value.
@throws \InvalidArgumentException If no values are given.
@throws MathException If an argument is not valid. | [
"Returns",
"the",
"minimum",
"of",
"the",
"given",
"values",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigNumber.php#L154-L171 |
brick/math | src/BigNumber.php | BigNumber.max | public static function max(...$values) : BigNumber
{
$max = null;
foreach ($values as $value) {
$value = static::of($value);
if ($max === null || $value->isGreaterThan($max)) {
$max = $value;
}
}
if ($max === null) {
throw new \InvalidArgumentException(__METHOD__ . '() expects at least one value.');
}
return $max;
} | php | public static function max(...$values) : BigNumber
{
$max = null;
foreach ($values as $value) {
$value = static::of($value);
if ($max === null || $value->isGreaterThan($max)) {
$max = $value;
}
}
if ($max === null) {
throw new \InvalidArgumentException(__METHOD__ . '() expects at least one value.');
}
return $max;
} | [
"public",
"static",
"function",
"max",
"(",
"...",
"$",
"values",
")",
":",
"BigNumber",
"{",
"$",
"max",
"=",
"null",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"static",
"::",
"of",
"(",
"$",
"value",
"... | Returns the maximum of the given values.
@param BigNumber|number|string ...$values The numbers to compare. All the numbers need to be convertible
to an instance of the class this method is called on.
@return static The maximum value.
@throws \InvalidArgumentException If no values are given.
@throws MathException If an argument is not valid. | [
"Returns",
"the",
"maximum",
"of",
"the",
"given",
"values",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigNumber.php#L184-L201 |
brick/math | src/BigNumber.php | BigNumber.sum | public static function sum(...$values) : BigNumber
{
/** @var BigNumber|null $sum */
$sum = null;
foreach ($values as $value) {
$value = static::of($value);
if ($sum === null) {
$sum = $value;
} else {
$sum = self::add($sum, $value);
}
}
if ($sum === null) {
throw new \InvalidArgumentException(__METHOD__ . '() expects at least one value.');
}
return $sum;
} | php | public static function sum(...$values) : BigNumber
{
/** @var BigNumber|null $sum */
$sum = null;
foreach ($values as $value) {
$value = static::of($value);
if ($sum === null) {
$sum = $value;
} else {
$sum = self::add($sum, $value);
}
}
if ($sum === null) {
throw new \InvalidArgumentException(__METHOD__ . '() expects at least one value.');
}
return $sum;
} | [
"public",
"static",
"function",
"sum",
"(",
"...",
"$",
"values",
")",
":",
"BigNumber",
"{",
"/** @var BigNumber|null $sum */",
"$",
"sum",
"=",
"null",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"static",
"::",... | Returns the sum of the given values.
@param BigNumber|number|string ...$values The numbers to add. All the numbers need to be convertible
to an instance of the class this method is called on.
@return static The sum.
@throws \InvalidArgumentException If no values are given.
@throws MathException If an argument is not valid. | [
"Returns",
"the",
"sum",
"of",
"the",
"given",
"values",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigNumber.php#L214-L234 |
brick/math | src/BigNumber.php | BigNumber.add | private static function add(BigNumber $a, BigNumber $b) : BigNumber
{
if ($a instanceof BigRational) {
return $a->plus($b);
}
if ($b instanceof BigRational) {
return $b->plus($a);
}
if ($a instanceof BigDecimal) {
return $a->plus($b);
}
if ($b instanceof BigDecimal) {
return $b->plus($a);
}
/** @var BigInteger $a */
return $a->plus($b);
} | php | private static function add(BigNumber $a, BigNumber $b) : BigNumber
{
if ($a instanceof BigRational) {
return $a->plus($b);
}
if ($b instanceof BigRational) {
return $b->plus($a);
}
if ($a instanceof BigDecimal) {
return $a->plus($b);
}
if ($b instanceof BigDecimal) {
return $b->plus($a);
}
/** @var BigInteger $a */
return $a->plus($b);
} | [
"private",
"static",
"function",
"add",
"(",
"BigNumber",
"$",
"a",
",",
"BigNumber",
"$",
"b",
")",
":",
"BigNumber",
"{",
"if",
"(",
"$",
"a",
"instanceof",
"BigRational",
")",
"{",
"return",
"$",
"a",
"->",
"plus",
"(",
"$",
"b",
")",
";",
"}",
... | Adds two BigNumber instances in the correct order to avoid a RoundingNecessaryException.
@todo This could be better resolved by creating an abstract protected method in BigNumber, and leaving to
concrete classes the responsibility to perform the addition themselves or delegate it to the given number,
depending on their ability to perform the operation. This will also require a version bump because we're
potentially breaking custom BigNumber implementations (if any...)
@param BigNumber $a
@param BigNumber $b
@return BigNumber | [
"Adds",
"two",
"BigNumber",
"instances",
"in",
"the",
"correct",
"order",
"to",
"avoid",
"a",
"RoundingNecessaryException",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigNumber.php#L249-L270 |
brick/math | src/BigNumber.php | BigNumber.cleanUp | private static function cleanUp(string $number) : string
{
$firstChar = $number[0];
if ($firstChar === '+' || $firstChar === '-') {
$number = \substr($number, 1);
}
$number = \ltrim($number, '0');
if ($number === '') {
return '0';
}
if ($firstChar === '-') {
return '-' . $number;
}
return $number;
} | php | private static function cleanUp(string $number) : string
{
$firstChar = $number[0];
if ($firstChar === '+' || $firstChar === '-') {
$number = \substr($number, 1);
}
$number = \ltrim($number, '0');
if ($number === '') {
return '0';
}
if ($firstChar === '-') {
return '-' . $number;
}
return $number;
} | [
"private",
"static",
"function",
"cleanUp",
"(",
"string",
"$",
"number",
")",
":",
"string",
"{",
"$",
"firstChar",
"=",
"$",
"number",
"[",
"0",
"]",
";",
"if",
"(",
"$",
"firstChar",
"===",
"'+'",
"||",
"$",
"firstChar",
"===",
"'-'",
")",
"{",
... | Removes optional leading zeros and + sign from the given number.
@param string $number The number, validated as a non-empty string of digits with optional sign.
@return string | [
"Removes",
"optional",
"leading",
"zeros",
"and",
"+",
"sign",
"from",
"the",
"given",
"number",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigNumber.php#L279-L298 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.add | public function add(string $a, string $b) : string
{
$result = $a + $b;
if (is_int($result)) {
return (string) $result;
}
if ($a === '0') {
return $b;
}
if ($b === '0') {
return $a;
}
$this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg);
if ($aNeg === $bNeg) {
$result = $this->doAdd($aDig, $bDig);
} else {
$result = $this->doSub($aDig, $bDig);
}
if ($aNeg) {
$result = $this->neg($result);
}
return $result;
} | php | public function add(string $a, string $b) : string
{
$result = $a + $b;
if (is_int($result)) {
return (string) $result;
}
if ($a === '0') {
return $b;
}
if ($b === '0') {
return $a;
}
$this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg);
if ($aNeg === $bNeg) {
$result = $this->doAdd($aDig, $bDig);
} else {
$result = $this->doSub($aDig, $bDig);
}
if ($aNeg) {
$result = $this->neg($result);
}
return $result;
} | [
"public",
"function",
"add",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"string",
"{",
"$",
"result",
"=",
"$",
"a",
"+",
"$",
"b",
";",
"if",
"(",
"is_int",
"(",
"$",
"result",
")",
")",
"{",
"return",
"(",
"string",
")",
"$... | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L52-L81 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.sub | public function sub(string $a, string $b) : string
{
return $this->add($a, $this->neg($b));
} | php | public function sub(string $a, string $b) : string
{
return $this->add($a, $this->neg($b));
} | [
"public",
"function",
"sub",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"string",
"{",
"return",
"$",
"this",
"->",
"add",
"(",
"$",
"a",
",",
"$",
"this",
"->",
"neg",
"(",
"$",
"b",
")",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L86-L89 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.mul | public function mul(string $a, string $b) : string
{
$result = $a * $b;
if (is_int($result)) {
return (string) $result;
}
if ($a === '0' || $b === '0') {
return '0';
}
if ($a === '1') {
return $b;
}
if ($b === '1') {
return $a;
}
if ($a === '-1') {
return $this->neg($b);
}
if ($b === '-1') {
return $this->neg($a);
}
$this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg);
$result = $this->doMul($aDig, $bDig);
if ($aNeg !== $bNeg) {
$result = $this->neg($result);
}
return $result;
} | php | public function mul(string $a, string $b) : string
{
$result = $a * $b;
if (is_int($result)) {
return (string) $result;
}
if ($a === '0' || $b === '0') {
return '0';
}
if ($a === '1') {
return $b;
}
if ($b === '1') {
return $a;
}
if ($a === '-1') {
return $this->neg($b);
}
if ($b === '-1') {
return $this->neg($a);
}
$this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg);
$result = $this->doMul($aDig, $bDig);
if ($aNeg !== $bNeg) {
$result = $this->neg($result);
}
return $result;
} | [
"public",
"function",
"mul",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"string",
"{",
"$",
"result",
"=",
"$",
"a",
"*",
"$",
"b",
";",
"if",
"(",
"is_int",
"(",
"$",
"result",
")",
")",
"{",
"return",
"(",
"string",
")",
"$... | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L94-L131 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.divQ | public function divQ(string $a, string $b) : string
{
return $this->divQR($a, $b)[0];
} | php | public function divQ(string $a, string $b) : string
{
return $this->divQR($a, $b)[0];
} | [
"public",
"function",
"divQ",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"string",
"{",
"return",
"$",
"this",
"->",
"divQR",
"(",
"$",
"a",
",",
"$",
"b",
")",
"[",
"0",
"]",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L136-L139 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.divR | public function divR(string $a, string $b): string
{
return $this->divQR($a, $b)[1];
} | php | public function divR(string $a, string $b): string
{
return $this->divQR($a, $b)[1];
} | [
"public",
"function",
"divR",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"string",
"{",
"return",
"$",
"this",
"->",
"divQR",
"(",
"$",
"a",
",",
"$",
"b",
")",
"[",
"1",
"]",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L144-L147 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.divQR | public function divQR(string $a, string $b) : array
{
if ($a === '0') {
return ['0', '0'];
}
if ($a === $b) {
return ['1', '0'];
}
if ($b === '1') {
return [$a, '0'];
}
if ($b === '-1') {
return [$this->neg($a), '0'];
}
$na = $a * 1; // cast to number
if (is_int($na)) {
$nb = $b * 1;
if (is_int($nb)) {
// the only division that may overflow is PHP_INT_MIN / -1,
// which cannot happen here as we've already handled a divisor of -1 above.
$r = $na % $nb;
$q = ($na - $r) / $nb;
assert(is_int($q));
return [
(string) $q,
(string) $r
];
}
}
$this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg);
[$q, $r] = $this->doDiv($aDig, $bDig);
if ($aNeg !== $bNeg) {
$q = $this->neg($q);
}
if ($aNeg) {
$r = $this->neg($r);
}
return [$q, $r];
} | php | public function divQR(string $a, string $b) : array
{
if ($a === '0') {
return ['0', '0'];
}
if ($a === $b) {
return ['1', '0'];
}
if ($b === '1') {
return [$a, '0'];
}
if ($b === '-1') {
return [$this->neg($a), '0'];
}
$na = $a * 1; // cast to number
if (is_int($na)) {
$nb = $b * 1;
if (is_int($nb)) {
// the only division that may overflow is PHP_INT_MIN / -1,
// which cannot happen here as we've already handled a divisor of -1 above.
$r = $na % $nb;
$q = ($na - $r) / $nb;
assert(is_int($q));
return [
(string) $q,
(string) $r
];
}
}
$this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg);
[$q, $r] = $this->doDiv($aDig, $bDig);
if ($aNeg !== $bNeg) {
$q = $this->neg($q);
}
if ($aNeg) {
$r = $this->neg($r);
}
return [$q, $r];
} | [
"public",
"function",
"divQR",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"array",
"{",
"if",
"(",
"$",
"a",
"===",
"'0'",
")",
"{",
"return",
"[",
"'0'",
",",
"'0'",
"]",
";",
"}",
"if",
"(",
"$",
"a",
"===",
"$",
"b",
")"... | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L152-L203 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.pow | public function pow(string $a, int $e) : string
{
if ($e === 0) {
return '1';
}
if ($e === 1) {
return $a;
}
$odd = $e % 2;
$e -= $odd;
$aa = $this->mul($a, $a);
$result = $this->pow($aa, $e / 2);
if ($odd === 1) {
$result = $this->mul($result, $a);
}
return $result;
} | php | public function pow(string $a, int $e) : string
{
if ($e === 0) {
return '1';
}
if ($e === 1) {
return $a;
}
$odd = $e % 2;
$e -= $odd;
$aa = $this->mul($a, $a);
$result = $this->pow($aa, $e / 2);
if ($odd === 1) {
$result = $this->mul($result, $a);
}
return $result;
} | [
"public",
"function",
"pow",
"(",
"string",
"$",
"a",
",",
"int",
"$",
"e",
")",
":",
"string",
"{",
"if",
"(",
"$",
"e",
"===",
"0",
")",
"{",
"return",
"'1'",
";",
"}",
"if",
"(",
"$",
"e",
"===",
"1",
")",
"{",
"return",
"$",
"a",
";",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L208-L229 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.sqrt | public function sqrt(string $n) : string
{
if ($n === '0') {
return '0';
}
// initial approximation
$x = \str_repeat('9', \intdiv(\strlen($n), 2) ?: 1);
$decreased = false;
for (;;) {
$nx = $this->divQ($this->add($x, $this->divQ($n, $x)), '2');
if ($x === $nx || $this->cmp($nx, $x) > 0 && $decreased) {
break;
}
$decreased = $this->cmp($nx, $x) < 0;
$x = $nx;
}
return $x;
} | php | public function sqrt(string $n) : string
{
if ($n === '0') {
return '0';
}
// initial approximation
$x = \str_repeat('9', \intdiv(\strlen($n), 2) ?: 1);
$decreased = false;
for (;;) {
$nx = $this->divQ($this->add($x, $this->divQ($n, $x)), '2');
if ($x === $nx || $this->cmp($nx, $x) > 0 && $decreased) {
break;
}
$decreased = $this->cmp($nx, $x) < 0;
$x = $nx;
}
return $x;
} | [
"public",
"function",
"sqrt",
"(",
"string",
"$",
"n",
")",
":",
"string",
"{",
"if",
"(",
"$",
"n",
"===",
"'0'",
")",
"{",
"return",
"'0'",
";",
"}",
"// initial approximation",
"$",
"x",
"=",
"\\",
"str_repeat",
"(",
"'9'",
",",
"\\",
"intdiv",
... | Adapted from https://cp-algorithms.com/num_methods/roots_newton.html
{@inheritDoc} | [
"Adapted",
"from",
"https",
":",
"//",
"cp",
"-",
"algorithms",
".",
"com",
"/",
"num_methods",
"/",
"roots_newton",
".",
"html"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L236-L259 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.doAdd | private function doAdd(string $a, string $b) : string
{
$length = $this->pad($a, $b);
$carry = 0;
$result = '';
for ($i = $length - $this->maxDigits;; $i -= $this->maxDigits) {
$blockLength = $this->maxDigits;
if ($i < 0) {
$blockLength += $i;
$i = 0;
}
$blockA = \substr($a, $i, $blockLength);
$blockB = \substr($b, $i, $blockLength);
$sum = (string) ($blockA + $blockB + $carry);
$sumLength = \strlen($sum);
if ($sumLength > $blockLength) {
$sum = \substr($sum, 1);
$carry = 1;
} else {
if ($sumLength < $blockLength) {
$sum = \str_repeat('0', $blockLength - $sumLength) . $sum;
}
$carry = 0;
}
$result = $sum . $result;
if ($i === 0) {
break;
}
}
if ($carry === 1) {
$result = '1' . $result;
}
return $result;
} | php | private function doAdd(string $a, string $b) : string
{
$length = $this->pad($a, $b);
$carry = 0;
$result = '';
for ($i = $length - $this->maxDigits;; $i -= $this->maxDigits) {
$blockLength = $this->maxDigits;
if ($i < 0) {
$blockLength += $i;
$i = 0;
}
$blockA = \substr($a, $i, $blockLength);
$blockB = \substr($b, $i, $blockLength);
$sum = (string) ($blockA + $blockB + $carry);
$sumLength = \strlen($sum);
if ($sumLength > $blockLength) {
$sum = \substr($sum, 1);
$carry = 1;
} else {
if ($sumLength < $blockLength) {
$sum = \str_repeat('0', $blockLength - $sumLength) . $sum;
}
$carry = 0;
}
$result = $sum . $result;
if ($i === 0) {
break;
}
}
if ($carry === 1) {
$result = '1' . $result;
}
return $result;
} | [
"private",
"function",
"doAdd",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"string",
"{",
"$",
"length",
"=",
"$",
"this",
"->",
"pad",
"(",
"$",
"a",
",",
"$",
"b",
")",
";",
"$",
"carry",
"=",
"0",
";",
"$",
"result",
"=",
... | Performs the addition of two non-signed large integers.
@param string $a The first operand.
@param string $b The second operand.
@return string | [
"Performs",
"the",
"addition",
"of",
"two",
"non",
"-",
"signed",
"large",
"integers",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L269-L312 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.doSub | private function doSub(string $a, string $b) : string
{
if ($a === $b) {
return '0';
}
// Ensure that we always subtract to a positive result: biggest minus smallest.
$cmp = $this->doCmp($a, $b);
$invert = ($cmp === -1);
if ($invert) {
$c = $a;
$a = $b;
$b = $c;
}
$length = $this->pad($a, $b);
$carry = 0;
$result = '';
$complement = 10 ** $this->maxDigits;
for ($i = $length - $this->maxDigits;; $i -= $this->maxDigits) {
$blockLength = $this->maxDigits;
if ($i < 0) {
$blockLength += $i;
$i = 0;
}
$blockA = \substr($a, $i, $blockLength);
$blockB = \substr($b, $i, $blockLength);
$sum = $blockA - $blockB - $carry;
if ($sum < 0) {
$sum += $complement;
$carry = 1;
} else {
$carry = 0;
}
$sum = (string) $sum;
$sumLength = \strlen($sum);
if ($sumLength < $blockLength) {
$sum = \str_repeat('0', $blockLength - $sumLength) . $sum;
}
$result = $sum . $result;
if ($i === 0) {
break;
}
}
// Carry cannot be 1 when the loop ends, as a > b
assert($carry === 0);
$result = \ltrim($result, '0');
if ($invert) {
$result = $this->neg($result);
}
return $result;
} | php | private function doSub(string $a, string $b) : string
{
if ($a === $b) {
return '0';
}
// Ensure that we always subtract to a positive result: biggest minus smallest.
$cmp = $this->doCmp($a, $b);
$invert = ($cmp === -1);
if ($invert) {
$c = $a;
$a = $b;
$b = $c;
}
$length = $this->pad($a, $b);
$carry = 0;
$result = '';
$complement = 10 ** $this->maxDigits;
for ($i = $length - $this->maxDigits;; $i -= $this->maxDigits) {
$blockLength = $this->maxDigits;
if ($i < 0) {
$blockLength += $i;
$i = 0;
}
$blockA = \substr($a, $i, $blockLength);
$blockB = \substr($b, $i, $blockLength);
$sum = $blockA - $blockB - $carry;
if ($sum < 0) {
$sum += $complement;
$carry = 1;
} else {
$carry = 0;
}
$sum = (string) $sum;
$sumLength = \strlen($sum);
if ($sumLength < $blockLength) {
$sum = \str_repeat('0', $blockLength - $sumLength) . $sum;
}
$result = $sum . $result;
if ($i === 0) {
break;
}
}
// Carry cannot be 1 when the loop ends, as a > b
assert($carry === 0);
$result = \ltrim($result, '0');
if ($invert) {
$result = $this->neg($result);
}
return $result;
} | [
"private",
"function",
"doSub",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"string",
"{",
"if",
"(",
"$",
"a",
"===",
"$",
"b",
")",
"{",
"return",
"'0'",
";",
"}",
"// Ensure that we always subtract to a positive result: biggest minus smalles... | Performs the subtraction of two non-signed large integers.
@param string $a The first operand.
@param string $b The second operand.
@return string | [
"Performs",
"the",
"subtraction",
"of",
"two",
"non",
"-",
"signed",
"large",
"integers",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L322-L390 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.doMul | private function doMul(string $a, string $b) : string
{
$x = \strlen($a);
$y = \strlen($b);
$maxDigits = \intdiv($this->maxDigits, 2);
$complement = 10 ** $maxDigits;
$result = '0';
for ($i = $x - $maxDigits;; $i -= $maxDigits) {
$blockALength = $maxDigits;
if ($i < 0) {
$blockALength += $i;
$i = 0;
}
$blockA = (int) \substr($a, $i, $blockALength);
$line = '';
$carry = 0;
for ($j = $y - $maxDigits;; $j -= $maxDigits) {
$blockBLength = $maxDigits;
if ($j < 0) {
$blockBLength += $j;
$j = 0;
}
$blockB = (int) \substr($b, $j, $blockBLength);
$mul = $blockA * $blockB + $carry;
$value = $mul % $complement;
$carry = ($mul - $value) / $complement;
$value = (string) $value;
$value = \str_pad($value, $maxDigits, '0', STR_PAD_LEFT);
$line = $value . $line;
if ($j === 0) {
break;
}
}
if ($carry !== 0) {
$line = $carry . $line;
}
$line = \ltrim($line, '0');
if ($line !== '') {
$line .= \str_repeat('0', $x - $blockALength - $i);
$result = $this->add($result, $line);
}
if ($i === 0) {
break;
}
}
return $result;
} | php | private function doMul(string $a, string $b) : string
{
$x = \strlen($a);
$y = \strlen($b);
$maxDigits = \intdiv($this->maxDigits, 2);
$complement = 10 ** $maxDigits;
$result = '0';
for ($i = $x - $maxDigits;; $i -= $maxDigits) {
$blockALength = $maxDigits;
if ($i < 0) {
$blockALength += $i;
$i = 0;
}
$blockA = (int) \substr($a, $i, $blockALength);
$line = '';
$carry = 0;
for ($j = $y - $maxDigits;; $j -= $maxDigits) {
$blockBLength = $maxDigits;
if ($j < 0) {
$blockBLength += $j;
$j = 0;
}
$blockB = (int) \substr($b, $j, $blockBLength);
$mul = $blockA * $blockB + $carry;
$value = $mul % $complement;
$carry = ($mul - $value) / $complement;
$value = (string) $value;
$value = \str_pad($value, $maxDigits, '0', STR_PAD_LEFT);
$line = $value . $line;
if ($j === 0) {
break;
}
}
if ($carry !== 0) {
$line = $carry . $line;
}
$line = \ltrim($line, '0');
if ($line !== '') {
$line .= \str_repeat('0', $x - $blockALength - $i);
$result = $this->add($result, $line);
}
if ($i === 0) {
break;
}
}
return $result;
} | [
"private",
"function",
"doMul",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"string",
"{",
"$",
"x",
"=",
"\\",
"strlen",
"(",
"$",
"a",
")",
";",
"$",
"y",
"=",
"\\",
"strlen",
"(",
"$",
"b",
")",
";",
"$",
"maxDigits",
"=",
... | Performs the multiplication of two non-signed large integers.
@param string $a The first operand.
@param string $b The second operand.
@return string | [
"Performs",
"the",
"multiplication",
"of",
"two",
"non",
"-",
"signed",
"large",
"integers",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L400-L464 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.doDiv | private function doDiv(string $a, string $b) : array
{
$cmp = $this->doCmp($a, $b);
if ($cmp === -1) {
return ['0', $a];
}
$x = \strlen($a);
$y = \strlen($b);
// we now know that a >= b && x >= y
$q = '0'; // quotient
$r = $a; // remainder
$z = $y; // focus length, always $y or $y+1
for (;;) {
$focus = \substr($a, 0, $z);
$cmp = $this->doCmp($focus, $b);
if ($cmp === -1) {
if ($z === $x) { // remainder < dividend
break;
}
$z++;
}
$zeros = \str_repeat('0', $x - $z);
$q = $this->add($q, '1' . $zeros);
$a = $this->sub($a, $b . $zeros);
$r = $a;
if ($r === '0') { // remainder == 0
break;
}
$x = \strlen($a);
if ($x < $y) { // remainder < dividend
break;
}
$z = $y;
}
return [$q, $r];
} | php | private function doDiv(string $a, string $b) : array
{
$cmp = $this->doCmp($a, $b);
if ($cmp === -1) {
return ['0', $a];
}
$x = \strlen($a);
$y = \strlen($b);
// we now know that a >= b && x >= y
$q = '0'; // quotient
$r = $a; // remainder
$z = $y; // focus length, always $y or $y+1
for (;;) {
$focus = \substr($a, 0, $z);
$cmp = $this->doCmp($focus, $b);
if ($cmp === -1) {
if ($z === $x) { // remainder < dividend
break;
}
$z++;
}
$zeros = \str_repeat('0', $x - $z);
$q = $this->add($q, '1' . $zeros);
$a = $this->sub($a, $b . $zeros);
$r = $a;
if ($r === '0') { // remainder == 0
break;
}
$x = \strlen($a);
if ($x < $y) { // remainder < dividend
break;
}
$z = $y;
}
return [$q, $r];
} | [
"private",
"function",
"doDiv",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"array",
"{",
"$",
"cmp",
"=",
"$",
"this",
"->",
"doCmp",
"(",
"$",
"a",
",",
"$",
"b",
")",
";",
"if",
"(",
"$",
"cmp",
"===",
"-",
"1",
")",
"{",... | Performs the division of two non-signed large integers.
@param string $a The first operand.
@param string $b The second operand.
@return string[] The quotient and remainder. | [
"Performs",
"the",
"division",
"of",
"two",
"non",
"-",
"signed",
"large",
"integers",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L474-L525 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.doCmp | private function doCmp(string $a, string $b) : int
{
$x = \strlen($a);
$y = \strlen($b);
$cmp = $x <=> $y;
if ($cmp !== 0) {
return $cmp;
}
return \strcmp($a, $b) <=> 0; // enforce [-1, 0, 1]
} | php | private function doCmp(string $a, string $b) : int
{
$x = \strlen($a);
$y = \strlen($b);
$cmp = $x <=> $y;
if ($cmp !== 0) {
return $cmp;
}
return \strcmp($a, $b) <=> 0; // enforce [-1, 0, 1]
} | [
"private",
"function",
"doCmp",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"int",
"{",
"$",
"x",
"=",
"\\",
"strlen",
"(",
"$",
"a",
")",
";",
"$",
"y",
"=",
"\\",
"strlen",
"(",
"$",
"b",
")",
";",
"$",
"cmp",
"=",
"$",
... | Compares two non-signed large numbers.
@param string $a The first operand.
@param string $b The second operand.
@return int [-1, 0, 1] | [
"Compares",
"two",
"non",
"-",
"signed",
"large",
"numbers",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L535-L547 |
brick/math | src/Internal/Calculator/NativeCalculator.php | NativeCalculator.pad | private function pad(string & $a, string & $b) : int
{
$x = \strlen($a);
$y = \strlen($b);
if ($x > $y) {
$b = \str_repeat('0', $x - $y) . $b;
return $x;
}
if ($x < $y) {
$a = \str_repeat('0', $y - $x) . $a;
return $y;
}
return $x;
} | php | private function pad(string & $a, string & $b) : int
{
$x = \strlen($a);
$y = \strlen($b);
if ($x > $y) {
$b = \str_repeat('0', $x - $y) . $b;
return $x;
}
if ($x < $y) {
$a = \str_repeat('0', $y - $x) . $a;
return $y;
}
return $x;
} | [
"private",
"function",
"pad",
"(",
"string",
"&",
"$",
"a",
",",
"string",
"&",
"$",
"b",
")",
":",
"int",
"{",
"$",
"x",
"=",
"\\",
"strlen",
"(",
"$",
"a",
")",
";",
"$",
"y",
"=",
"\\",
"strlen",
"(",
"$",
"b",
")",
";",
"if",
"(",
"$"... | Pads the left of one of the given numbers with zeros if necessary to make both numbers the same length.
The numbers must only consist of digits, without leading minus sign.
@param string $a The first operand.
@param string $b The second operand.
@return int The length of both strings. | [
"Pads",
"the",
"left",
"of",
"one",
"of",
"the",
"given",
"numbers",
"with",
"zeros",
"if",
"necessary",
"to",
"make",
"both",
"numbers",
"the",
"same",
"length",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator/NativeCalculator.php#L559-L577 |
brick/math | src/BigDecimal.php | BigDecimal.ofUnscaledValue | public static function ofUnscaledValue($value, int $scale = 0) : BigDecimal
{
if ($scale < 0) {
throw new \InvalidArgumentException('The scale cannot be negative.');
}
return new BigDecimal((string) BigInteger::of($value), $scale);
} | php | public static function ofUnscaledValue($value, int $scale = 0) : BigDecimal
{
if ($scale < 0) {
throw new \InvalidArgumentException('The scale cannot be negative.');
}
return new BigDecimal((string) BigInteger::of($value), $scale);
} | [
"public",
"static",
"function",
"ofUnscaledValue",
"(",
"$",
"value",
",",
"int",
"$",
"scale",
"=",
"0",
")",
":",
"BigDecimal",
"{",
"if",
"(",
"$",
"scale",
"<",
"0",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'The scale cannot be... | Creates a BigDecimal from an unscaled value and a scale.
Example: `(12345, 3)` will result in the BigDecimal `12.345`.
@param BigNumber|number|string $value The unscaled value. Must be convertible to a BigInteger.
@param int $scale The scale of the number, positive or zero.
@return BigDecimal
@throws \InvalidArgumentException If the scale is negative. | [
"Creates",
"a",
"BigDecimal",
"from",
"an",
"unscaled",
"value",
"and",
"a",
"scale",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L75-L82 |
brick/math | src/BigDecimal.php | BigDecimal.plus | public function plus($that) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->value === '0' && $that->scale <= $this->scale) {
return $this;
}
$this->scaleValues($this, $that, $a, $b);
$value = Calculator::get()->add($a, $b);
$scale = $this->scale > $that->scale ? $this->scale : $that->scale;
return new BigDecimal($value, $scale);
} | php | public function plus($that) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->value === '0' && $that->scale <= $this->scale) {
return $this;
}
$this->scaleValues($this, $that, $a, $b);
$value = Calculator::get()->add($a, $b);
$scale = $this->scale > $that->scale ? $this->scale : $that->scale;
return new BigDecimal($value, $scale);
} | [
"public",
"function",
"plus",
"(",
"$",
"that",
")",
":",
"BigDecimal",
"{",
"$",
"that",
"=",
"BigDecimal",
"::",
"of",
"(",
"$",
"that",
")",
";",
"if",
"(",
"$",
"that",
"->",
"value",
"===",
"'0'",
"&&",
"$",
"that",
"->",
"scale",
"<=",
"$",... | Returns the sum of this number and the given one.
The result has a scale of `max($this->scale, $that->scale)`.
@param BigNumber|number|string $that The number to add. Must be convertible to a BigDecimal.
@return BigDecimal The result.
@throws MathException If the number is not valid, or is not convertible to a BigDecimal. | [
"Returns",
"the",
"sum",
"of",
"this",
"number",
"and",
"the",
"given",
"one",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L143-L157 |
brick/math | src/BigDecimal.php | BigDecimal.minus | public function minus($that) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->value === '0' && $that->scale <= $this->scale) {
return $this;
}
$this->scaleValues($this, $that, $a, $b);
$value = Calculator::get()->sub($a, $b);
$scale = $this->scale > $that->scale ? $this->scale : $that->scale;
return new BigDecimal($value, $scale);
} | php | public function minus($that) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->value === '0' && $that->scale <= $this->scale) {
return $this;
}
$this->scaleValues($this, $that, $a, $b);
$value = Calculator::get()->sub($a, $b);
$scale = $this->scale > $that->scale ? $this->scale : $that->scale;
return new BigDecimal($value, $scale);
} | [
"public",
"function",
"minus",
"(",
"$",
"that",
")",
":",
"BigDecimal",
"{",
"$",
"that",
"=",
"BigDecimal",
"::",
"of",
"(",
"$",
"that",
")",
";",
"if",
"(",
"$",
"that",
"->",
"value",
"===",
"'0'",
"&&",
"$",
"that",
"->",
"scale",
"<=",
"$"... | Returns the difference of this number and the given one.
The result has a scale of `max($this->scale, $that->scale)`.
@param BigNumber|number|string $that The number to subtract. Must be convertible to a BigDecimal.
@return BigDecimal The result.
@throws MathException If the number is not valid, or is not convertible to a BigDecimal. | [
"Returns",
"the",
"difference",
"of",
"this",
"number",
"and",
"the",
"given",
"one",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L170-L184 |
brick/math | src/BigDecimal.php | BigDecimal.multipliedBy | public function multipliedBy($that) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->value === '1' && $that->scale === 0) {
return $this;
}
$value = Calculator::get()->mul($this->value, $that->value);
$scale = $this->scale + $that->scale;
return new BigDecimal($value, $scale);
} | php | public function multipliedBy($that) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->value === '1' && $that->scale === 0) {
return $this;
}
$value = Calculator::get()->mul($this->value, $that->value);
$scale = $this->scale + $that->scale;
return new BigDecimal($value, $scale);
} | [
"public",
"function",
"multipliedBy",
"(",
"$",
"that",
")",
":",
"BigDecimal",
"{",
"$",
"that",
"=",
"BigDecimal",
"::",
"of",
"(",
"$",
"that",
")",
";",
"if",
"(",
"$",
"that",
"->",
"value",
"===",
"'1'",
"&&",
"$",
"that",
"->",
"scale",
"===... | Returns the product of this number and the given one.
The result has a scale of `$this->scale + $that->scale`.
@param BigNumber|number|string $that The multiplier. Must be convertible to a BigDecimal.
@return BigDecimal The result.
@throws MathException If the multiplier is not a valid number, or is not convertible to a BigDecimal. | [
"Returns",
"the",
"product",
"of",
"this",
"number",
"and",
"the",
"given",
"one",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L197-L209 |
brick/math | src/BigDecimal.php | BigDecimal.dividedBy | public function dividedBy($that, int $scale = null, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->isZero()) {
throw DivisionByZeroException::divisionByZero();
}
if ($scale === null) {
$scale = $this->scale;
} elseif ($scale < 0) {
throw new \InvalidArgumentException('Scale cannot be negative.');
}
if ($that->value === '1' && $that->scale === 0 && $scale === $this->scale) {
return $this;
}
$p = $this->valueWithMinScale($that->scale + $scale);
$q = $that->valueWithMinScale($this->scale - $scale);
$result = Calculator::get()->divRound($p, $q, $roundingMode);
return new BigDecimal($result, $scale);
} | php | public function dividedBy($that, int $scale = null, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->isZero()) {
throw DivisionByZeroException::divisionByZero();
}
if ($scale === null) {
$scale = $this->scale;
} elseif ($scale < 0) {
throw new \InvalidArgumentException('Scale cannot be negative.');
}
if ($that->value === '1' && $that->scale === 0 && $scale === $this->scale) {
return $this;
}
$p = $this->valueWithMinScale($that->scale + $scale);
$q = $that->valueWithMinScale($this->scale - $scale);
$result = Calculator::get()->divRound($p, $q, $roundingMode);
return new BigDecimal($result, $scale);
} | [
"public",
"function",
"dividedBy",
"(",
"$",
"that",
",",
"int",
"$",
"scale",
"=",
"null",
",",
"int",
"$",
"roundingMode",
"=",
"RoundingMode",
"::",
"UNNECESSARY",
")",
":",
"BigDecimal",
"{",
"$",
"that",
"=",
"BigDecimal",
"::",
"of",
"(",
"$",
"t... | Returns the result of the division of this number by the given one, at the given scale.
@param BigNumber|number|string $that The divisor.
@param int|null $scale The desired scale, or null to use the scale of this number.
@param int $roundingMode An optional rounding mode.
@return BigDecimal
@throws \InvalidArgumentException If the scale or rounding mode is invalid.
@throws MathException If the number is invalid, is zero, or rounding was necessary. | [
"Returns",
"the",
"result",
"of",
"the",
"division",
"of",
"this",
"number",
"by",
"the",
"given",
"one",
"at",
"the",
"given",
"scale",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L223-L247 |
brick/math | src/BigDecimal.php | BigDecimal.exactlyDividedBy | public function exactlyDividedBy($that) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->value === '0') {
throw DivisionByZeroException::divisionByZero();
}
$this->scaleValues($this, $that, $a, $b);
$d = \rtrim($b, '0');
$scale = \strlen($b) - \strlen($d);
$calculator = Calculator::get();
foreach ([5, 2] as $prime) {
for (;;) {
$lastDigit = (int) $d[-1];
if ($lastDigit % $prime !== 0) {
break;
}
$d = $calculator->divQ($d, (string) $prime);
$scale++;
}
}
return $this->dividedBy($that, $scale)->stripTrailingZeros();
} | php | public function exactlyDividedBy($that) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->value === '0') {
throw DivisionByZeroException::divisionByZero();
}
$this->scaleValues($this, $that, $a, $b);
$d = \rtrim($b, '0');
$scale = \strlen($b) - \strlen($d);
$calculator = Calculator::get();
foreach ([5, 2] as $prime) {
for (;;) {
$lastDigit = (int) $d[-1];
if ($lastDigit % $prime !== 0) {
break;
}
$d = $calculator->divQ($d, (string) $prime);
$scale++;
}
}
return $this->dividedBy($that, $scale)->stripTrailingZeros();
} | [
"public",
"function",
"exactlyDividedBy",
"(",
"$",
"that",
")",
":",
"BigDecimal",
"{",
"$",
"that",
"=",
"BigDecimal",
"::",
"of",
"(",
"$",
"that",
")",
";",
"if",
"(",
"$",
"that",
"->",
"value",
"===",
"'0'",
")",
"{",
"throw",
"DivisionByZeroExce... | Returns the exact result of the division of this number by the given one.
The scale of the result is automatically calculated to fit all the fraction digits.
@param BigNumber|number|string $that The divisor. Must be convertible to a BigDecimal.
@return BigDecimal The result.
@throws MathException If the divisor is not a valid number, is not convertible to a BigDecimal, is zero,
or the result yields an infinite number of digits. | [
"Returns",
"the",
"exact",
"result",
"of",
"the",
"division",
"of",
"this",
"number",
"by",
"the",
"given",
"one",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L261-L290 |
brick/math | src/BigDecimal.php | BigDecimal.power | public function power(int $exponent) : BigDecimal
{
if ($exponent === 0) {
return BigDecimal::one();
}
if ($exponent === 1) {
return $this;
}
if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
throw new \InvalidArgumentException(\sprintf(
'The exponent %d is not in the range 0 to %d.',
$exponent,
Calculator::MAX_POWER
));
}
return new BigDecimal(Calculator::get()->pow($this->value, $exponent), $this->scale * $exponent);
} | php | public function power(int $exponent) : BigDecimal
{
if ($exponent === 0) {
return BigDecimal::one();
}
if ($exponent === 1) {
return $this;
}
if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
throw new \InvalidArgumentException(\sprintf(
'The exponent %d is not in the range 0 to %d.',
$exponent,
Calculator::MAX_POWER
));
}
return new BigDecimal(Calculator::get()->pow($this->value, $exponent), $this->scale * $exponent);
} | [
"public",
"function",
"power",
"(",
"int",
"$",
"exponent",
")",
":",
"BigDecimal",
"{",
"if",
"(",
"$",
"exponent",
"===",
"0",
")",
"{",
"return",
"BigDecimal",
"::",
"one",
"(",
")",
";",
"}",
"if",
"(",
"$",
"exponent",
"===",
"1",
")",
"{",
... | Returns this number exponentiated to the given value.
The result has a scale of `$this->scale * $exponent`.
@param int $exponent The exponent.
@return BigDecimal The result.
@throws \InvalidArgumentException If the exponent is not in the range 0 to 1,000,000. | [
"Returns",
"this",
"number",
"exponentiated",
"to",
"the",
"given",
"value",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L303-L322 |
brick/math | src/BigDecimal.php | BigDecimal.quotient | public function quotient($that) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->isZero()) {
throw DivisionByZeroException::divisionByZero();
}
$p = $this->valueWithMinScale($that->scale);
$q = $that->valueWithMinScale($this->scale);
$quotient = Calculator::get()->divQ($p, $q);
return new BigDecimal($quotient, 0);
} | php | public function quotient($that) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->isZero()) {
throw DivisionByZeroException::divisionByZero();
}
$p = $this->valueWithMinScale($that->scale);
$q = $that->valueWithMinScale($this->scale);
$quotient = Calculator::get()->divQ($p, $q);
return new BigDecimal($quotient, 0);
} | [
"public",
"function",
"quotient",
"(",
"$",
"that",
")",
":",
"BigDecimal",
"{",
"$",
"that",
"=",
"BigDecimal",
"::",
"of",
"(",
"$",
"that",
")",
";",
"if",
"(",
"$",
"that",
"->",
"isZero",
"(",
")",
")",
"{",
"throw",
"DivisionByZeroException",
"... | Returns the quotient of the division of this number by this given one.
The quotient has a scale of `0`.
@param BigNumber|number|string $that The divisor. Must be convertible to a BigDecimal.
@return BigDecimal The quotient.
@throws MathException If the divisor is not a valid decimal number, or is zero. | [
"Returns",
"the",
"quotient",
"of",
"the",
"division",
"of",
"this",
"number",
"by",
"this",
"given",
"one",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L335-L349 |
brick/math | src/BigDecimal.php | BigDecimal.remainder | public function remainder($that) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->isZero()) {
throw DivisionByZeroException::divisionByZero();
}
$p = $this->valueWithMinScale($that->scale);
$q = $that->valueWithMinScale($this->scale);
$remainder = Calculator::get()->divR($p, $q);
$scale = $this->scale > $that->scale ? $this->scale : $that->scale;
return new BigDecimal($remainder, $scale);
} | php | public function remainder($that) : BigDecimal
{
$that = BigDecimal::of($that);
if ($that->isZero()) {
throw DivisionByZeroException::divisionByZero();
}
$p = $this->valueWithMinScale($that->scale);
$q = $that->valueWithMinScale($this->scale);
$remainder = Calculator::get()->divR($p, $q);
$scale = $this->scale > $that->scale ? $this->scale : $that->scale;
return new BigDecimal($remainder, $scale);
} | [
"public",
"function",
"remainder",
"(",
"$",
"that",
")",
":",
"BigDecimal",
"{",
"$",
"that",
"=",
"BigDecimal",
"::",
"of",
"(",
"$",
"that",
")",
";",
"if",
"(",
"$",
"that",
"->",
"isZero",
"(",
")",
")",
"{",
"throw",
"DivisionByZeroException",
... | Returns the remainder of the division of this number by this given one.
The remainder has a scale of `max($this->scale, $that->scale)`.
@param BigNumber|number|string $that The divisor. Must be convertible to a BigDecimal.
@return BigDecimal The remainder.
@throws MathException If the divisor is not a valid decimal number, or is zero. | [
"Returns",
"the",
"remainder",
"of",
"the",
"division",
"of",
"this",
"number",
"by",
"this",
"given",
"one",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L362-L378 |
brick/math | src/BigDecimal.php | BigDecimal.quotientAndRemainder | public function quotientAndRemainder($that) : array
{
$that = BigDecimal::of($that);
if ($that->isZero()) {
throw DivisionByZeroException::divisionByZero();
}
$p = $this->valueWithMinScale($that->scale);
$q = $that->valueWithMinScale($this->scale);
[$quotient, $remainder] = Calculator::get()->divQR($p, $q);
$scale = $this->scale > $that->scale ? $this->scale : $that->scale;
$quotient = new BigDecimal($quotient, 0);
$remainder = new BigDecimal($remainder, $scale);
return [$quotient, $remainder];
} | php | public function quotientAndRemainder($that) : array
{
$that = BigDecimal::of($that);
if ($that->isZero()) {
throw DivisionByZeroException::divisionByZero();
}
$p = $this->valueWithMinScale($that->scale);
$q = $that->valueWithMinScale($this->scale);
[$quotient, $remainder] = Calculator::get()->divQR($p, $q);
$scale = $this->scale > $that->scale ? $this->scale : $that->scale;
$quotient = new BigDecimal($quotient, 0);
$remainder = new BigDecimal($remainder, $scale);
return [$quotient, $remainder];
} | [
"public",
"function",
"quotientAndRemainder",
"(",
"$",
"that",
")",
":",
"array",
"{",
"$",
"that",
"=",
"BigDecimal",
"::",
"of",
"(",
"$",
"that",
")",
";",
"if",
"(",
"$",
"that",
"->",
"isZero",
"(",
")",
")",
"{",
"throw",
"DivisionByZeroExceptio... | Returns the quotient and remainder of the division of this number by the given one.
The quotient has a scale of `0`, and the remainder has a scale of `max($this->scale, $that->scale)`.
@param BigNumber|number|string $that The divisor. Must be convertible to a BigDecimal.
@return BigDecimal[] An array containing the quotient and the remainder.
@throws MathException If the divisor is not a valid decimal number, or is zero. | [
"Returns",
"the",
"quotient",
"and",
"remainder",
"of",
"the",
"division",
"of",
"this",
"number",
"by",
"the",
"given",
"one",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L391-L410 |
brick/math | src/BigDecimal.php | BigDecimal.sqrt | public function sqrt(int $scale) : BigDecimal
{
if ($scale < 0) {
throw new \InvalidArgumentException('Scale cannot be negative.');
}
if ($this->value === '0') {
return new BigDecimal('0', $scale);
}
if ($this->value[0] === '-') {
throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
}
$value = $this->value;
$addDigits = 2 * $scale - $this->scale;
if ($addDigits > 0) {
// add zeros
$value .= \str_repeat('0', $addDigits);
} elseif ($addDigits < 0) {
// trim digits
if (-$addDigits >= \strlen($this->value)) {
// requesting a scale too low, will always yield a zero result
return new BigDecimal('0', $scale);
}
$value = \substr($value, 0, $addDigits);
}
$value = Calculator::get()->sqrt($value);
return new BigDecimal($value, $scale);
} | php | public function sqrt(int $scale) : BigDecimal
{
if ($scale < 0) {
throw new \InvalidArgumentException('Scale cannot be negative.');
}
if ($this->value === '0') {
return new BigDecimal('0', $scale);
}
if ($this->value[0] === '-') {
throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
}
$value = $this->value;
$addDigits = 2 * $scale - $this->scale;
if ($addDigits > 0) {
// add zeros
$value .= \str_repeat('0', $addDigits);
} elseif ($addDigits < 0) {
// trim digits
if (-$addDigits >= \strlen($this->value)) {
// requesting a scale too low, will always yield a zero result
return new BigDecimal('0', $scale);
}
$value = \substr($value, 0, $addDigits);
}
$value = Calculator::get()->sqrt($value);
return new BigDecimal($value, $scale);
} | [
"public",
"function",
"sqrt",
"(",
"int",
"$",
"scale",
")",
":",
"BigDecimal",
"{",
"if",
"(",
"$",
"scale",
"<",
"0",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Scale cannot be negative.'",
")",
";",
"}",
"if",
"(",
"$",
"this",... | Returns the square root of this number, rounded down to the given number of decimals.
@param int $scale
@return BigDecimal
@throws \InvalidArgumentException If the scale is negative.
@throws NegativeNumberException If this number is negative. | [
"Returns",
"the",
"square",
"root",
"of",
"this",
"number",
"rounded",
"down",
"to",
"the",
"given",
"number",
"of",
"decimals",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L422-L455 |
brick/math | src/BigDecimal.php | BigDecimal.withPointMovedLeft | public function withPointMovedLeft(int $n) : BigDecimal
{
if ($n === 0) {
return $this;
}
if ($n < 0) {
return $this->withPointMovedRight(-$n);
}
return new BigDecimal($this->value, $this->scale + $n);
} | php | public function withPointMovedLeft(int $n) : BigDecimal
{
if ($n === 0) {
return $this;
}
if ($n < 0) {
return $this->withPointMovedRight(-$n);
}
return new BigDecimal($this->value, $this->scale + $n);
} | [
"public",
"function",
"withPointMovedLeft",
"(",
"int",
"$",
"n",
")",
":",
"BigDecimal",
"{",
"if",
"(",
"$",
"n",
"===",
"0",
")",
"{",
"return",
"$",
"this",
";",
"}",
"if",
"(",
"$",
"n",
"<",
"0",
")",
"{",
"return",
"$",
"this",
"->",
"wi... | Returns a copy of this BigDecimal with the decimal point moved $n places to the left.
@param int $n
@return BigDecimal | [
"Returns",
"a",
"copy",
"of",
"this",
"BigDecimal",
"with",
"the",
"decimal",
"point",
"moved",
"$n",
"places",
"to",
"the",
"left",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L464-L475 |
brick/math | src/BigDecimal.php | BigDecimal.withPointMovedRight | public function withPointMovedRight(int $n) : BigDecimal
{
if ($n === 0) {
return $this;
}
if ($n < 0) {
return $this->withPointMovedLeft(-$n);
}
$value = $this->value;
$scale = $this->scale - $n;
if ($scale < 0) {
if ($value !== '0') {
$value .= \str_repeat('0', -$scale);
}
$scale = 0;
}
return new BigDecimal($value, $scale);
} | php | public function withPointMovedRight(int $n) : BigDecimal
{
if ($n === 0) {
return $this;
}
if ($n < 0) {
return $this->withPointMovedLeft(-$n);
}
$value = $this->value;
$scale = $this->scale - $n;
if ($scale < 0) {
if ($value !== '0') {
$value .= \str_repeat('0', -$scale);
}
$scale = 0;
}
return new BigDecimal($value, $scale);
} | [
"public",
"function",
"withPointMovedRight",
"(",
"int",
"$",
"n",
")",
":",
"BigDecimal",
"{",
"if",
"(",
"$",
"n",
"===",
"0",
")",
"{",
"return",
"$",
"this",
";",
"}",
"if",
"(",
"$",
"n",
"<",
"0",
")",
"{",
"return",
"$",
"this",
"->",
"w... | Returns a copy of this BigDecimal with the decimal point moved $n places to the right.
@param int $n
@return BigDecimal | [
"Returns",
"a",
"copy",
"of",
"this",
"BigDecimal",
"with",
"the",
"decimal",
"point",
"moved",
"$n",
"places",
"to",
"the",
"right",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L484-L505 |
brick/math | src/BigDecimal.php | BigDecimal.stripTrailingZeros | public function stripTrailingZeros() : BigDecimal
{
if ($this->scale === 0) {
return $this;
}
$trimmedValue = \rtrim($this->value, '0');
if ($trimmedValue === '') {
return BigDecimal::zero();
}
$trimmableZeros = \strlen($this->value) - \strlen($trimmedValue);
if ($trimmableZeros === 0) {
return $this;
}
if ($trimmableZeros > $this->scale) {
$trimmableZeros = $this->scale;
}
$value = \substr($this->value, 0, -$trimmableZeros);
$scale = $this->scale - $trimmableZeros;
return new BigDecimal($value, $scale);
} | php | public function stripTrailingZeros() : BigDecimal
{
if ($this->scale === 0) {
return $this;
}
$trimmedValue = \rtrim($this->value, '0');
if ($trimmedValue === '') {
return BigDecimal::zero();
}
$trimmableZeros = \strlen($this->value) - \strlen($trimmedValue);
if ($trimmableZeros === 0) {
return $this;
}
if ($trimmableZeros > $this->scale) {
$trimmableZeros = $this->scale;
}
$value = \substr($this->value, 0, -$trimmableZeros);
$scale = $this->scale - $trimmableZeros;
return new BigDecimal($value, $scale);
} | [
"public",
"function",
"stripTrailingZeros",
"(",
")",
":",
"BigDecimal",
"{",
"if",
"(",
"$",
"this",
"->",
"scale",
"===",
"0",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"trimmedValue",
"=",
"\\",
"rtrim",
"(",
"$",
"this",
"->",
"value",
",",... | Returns a copy of this BigDecimal with any trailing zeros removed from the fractional part.
@return BigDecimal | [
"Returns",
"a",
"copy",
"of",
"this",
"BigDecimal",
"with",
"any",
"trailing",
"zeros",
"removed",
"from",
"the",
"fractional",
"part",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L512-L538 |
brick/math | src/BigDecimal.php | BigDecimal.negated | public function negated() : BigDecimal
{
return new BigDecimal(Calculator::get()->neg($this->value), $this->scale);
} | php | public function negated() : BigDecimal
{
return new BigDecimal(Calculator::get()->neg($this->value), $this->scale);
} | [
"public",
"function",
"negated",
"(",
")",
":",
"BigDecimal",
"{",
"return",
"new",
"BigDecimal",
"(",
"Calculator",
"::",
"get",
"(",
")",
"->",
"neg",
"(",
"$",
"this",
"->",
"value",
")",
",",
"$",
"this",
"->",
"scale",
")",
";",
"}"
] | Returns the negated value of this number.
@return BigDecimal | [
"Returns",
"the",
"negated",
"value",
"of",
"this",
"number",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L555-L558 |
brick/math | src/BigDecimal.php | BigDecimal.compareTo | public function compareTo($that) : int
{
$that = BigNumber::of($that);
if ($that instanceof BigInteger) {
$that = $that->toBigDecimal();
}
if ($that instanceof BigDecimal) {
$this->scaleValues($this, $that, $a, $b);
return Calculator::get()->cmp($a, $b);
}
return - $that->compareTo($this);
} | php | public function compareTo($that) : int
{
$that = BigNumber::of($that);
if ($that instanceof BigInteger) {
$that = $that->toBigDecimal();
}
if ($that instanceof BigDecimal) {
$this->scaleValues($this, $that, $a, $b);
return Calculator::get()->cmp($a, $b);
}
return - $that->compareTo($this);
} | [
"public",
"function",
"compareTo",
"(",
"$",
"that",
")",
":",
"int",
"{",
"$",
"that",
"=",
"BigNumber",
"::",
"of",
"(",
"$",
"that",
")",
";",
"if",
"(",
"$",
"that",
"instanceof",
"BigInteger",
")",
"{",
"$",
"that",
"=",
"$",
"that",
"->",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L563-L578 |
brick/math | src/BigDecimal.php | BigDecimal.getIntegralPart | public function getIntegralPart() : string
{
if ($this->scale === 0) {
return $this->value;
}
$value = $this->getUnscaledValueWithLeadingZeros();
return \substr($value, 0, -$this->scale);
} | php | public function getIntegralPart() : string
{
if ($this->scale === 0) {
return $this->value;
}
$value = $this->getUnscaledValueWithLeadingZeros();
return \substr($value, 0, -$this->scale);
} | [
"public",
"function",
"getIntegralPart",
"(",
")",
":",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"scale",
"===",
"0",
")",
"{",
"return",
"$",
"this",
"->",
"value",
";",
"}",
"$",
"value",
"=",
"$",
"this",
"->",
"getUnscaledValueWithLeadingZeros",
... | Returns a string representing the integral part of this decimal number.
Example: `-123.456` => `-123`.
@return string | [
"Returns",
"a",
"string",
"representing",
"the",
"integral",
"part",
"of",
"this",
"decimal",
"number",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L611-L620 |
brick/math | src/BigDecimal.php | BigDecimal.getFractionalPart | public function getFractionalPart() : string
{
if ($this->scale === 0) {
return '';
}
$value = $this->getUnscaledValueWithLeadingZeros();
return \substr($value, -$this->scale);
} | php | public function getFractionalPart() : string
{
if ($this->scale === 0) {
return '';
}
$value = $this->getUnscaledValueWithLeadingZeros();
return \substr($value, -$this->scale);
} | [
"public",
"function",
"getFractionalPart",
"(",
")",
":",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"scale",
"===",
"0",
")",
"{",
"return",
"''",
";",
"}",
"$",
"value",
"=",
"$",
"this",
"->",
"getUnscaledValueWithLeadingZeros",
"(",
")",
";",
"re... | Returns a string representing the fractional part of this decimal number.
If the scale is zero, an empty string is returned.
Examples: `-123.456` => '456', `123` => ''.
@return string | [
"Returns",
"a",
"string",
"representing",
"the",
"fractional",
"part",
"of",
"this",
"decimal",
"number",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L631-L640 |
brick/math | src/BigDecimal.php | BigDecimal.toBigInteger | public function toBigInteger() : BigInteger
{
if ($this->scale === 0) {
$zeroScaleDecimal = $this;
} else {
$zeroScaleDecimal = $this->dividedBy(1, 0);
}
return BigInteger::create($zeroScaleDecimal->value);
} | php | public function toBigInteger() : BigInteger
{
if ($this->scale === 0) {
$zeroScaleDecimal = $this;
} else {
$zeroScaleDecimal = $this->dividedBy(1, 0);
}
return BigInteger::create($zeroScaleDecimal->value);
} | [
"public",
"function",
"toBigInteger",
"(",
")",
":",
"BigInteger",
"{",
"if",
"(",
"$",
"this",
"->",
"scale",
"===",
"0",
")",
"{",
"$",
"zeroScaleDecimal",
"=",
"$",
"this",
";",
"}",
"else",
"{",
"$",
"zeroScaleDecimal",
"=",
"$",
"this",
"->",
"d... | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L655-L664 |
brick/math | src/BigDecimal.php | BigDecimal.toBigRational | public function toBigRational() : BigRational
{
$numerator = BigInteger::create($this->value);
$denominator = BigInteger::create('1' . \str_repeat('0', $this->scale));
return BigRational::create($numerator, $denominator, false);
} | php | public function toBigRational() : BigRational
{
$numerator = BigInteger::create($this->value);
$denominator = BigInteger::create('1' . \str_repeat('0', $this->scale));
return BigRational::create($numerator, $denominator, false);
} | [
"public",
"function",
"toBigRational",
"(",
")",
":",
"BigRational",
"{",
"$",
"numerator",
"=",
"BigInteger",
"::",
"create",
"(",
"$",
"this",
"->",
"value",
")",
";",
"$",
"denominator",
"=",
"BigInteger",
"::",
"create",
"(",
"'1'",
".",
"\\",
"str_r... | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L677-L683 |
brick/math | src/BigDecimal.php | BigDecimal.toScale | public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal
{
if ($scale === $this->scale) {
return $this;
}
return $this->dividedBy(BigDecimal::one(), $scale, $roundingMode);
} | php | public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal
{
if ($scale === $this->scale) {
return $this;
}
return $this->dividedBy(BigDecimal::one(), $scale, $roundingMode);
} | [
"public",
"function",
"toScale",
"(",
"int",
"$",
"scale",
",",
"int",
"$",
"roundingMode",
"=",
"RoundingMode",
"::",
"UNNECESSARY",
")",
":",
"BigDecimal",
"{",
"if",
"(",
"$",
"scale",
"===",
"$",
"this",
"->",
"scale",
")",
"{",
"return",
"$",
"thi... | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L688-L695 |
brick/math | src/BigDecimal.php | BigDecimal.unserialize | public function unserialize($value) : void
{
if (isset($this->value)) {
throw new \LogicException('unserialize() is an internal function, it must not be called directly.');
}
[$value, $scale] = \explode(':', $value);
$this->value = $value;
$this->scale = (int) $scale;
} | php | public function unserialize($value) : void
{
if (isset($this->value)) {
throw new \LogicException('unserialize() is an internal function, it must not be called directly.');
}
[$value, $scale] = \explode(':', $value);
$this->value = $value;
$this->scale = (int) $scale;
} | [
"public",
"function",
"unserialize",
"(",
"$",
"value",
")",
":",
"void",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"value",
")",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'unserialize() is an internal function, it must not be called directly.... | This method is only here to implement interface Serializable and cannot be accessed directly.
@internal
@param string $value
@return void
@throws \LogicException | [
"This",
"method",
"is",
"only",
"here",
"to",
"implement",
"interface",
"Serializable",
"and",
"cannot",
"be",
"accessed",
"directly",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L750-L760 |
brick/math | src/BigDecimal.php | BigDecimal.scaleValues | private function scaleValues(BigDecimal $x, BigDecimal $y, & $a, & $b) : void
{
$a = $x->value;
$b = $y->value;
if ($b !== '0' && $x->scale > $y->scale) {
$b .= \str_repeat('0', $x->scale - $y->scale);
} elseif ($a !== '0' && $x->scale < $y->scale) {
$a .= \str_repeat('0', $y->scale - $x->scale);
}
} | php | private function scaleValues(BigDecimal $x, BigDecimal $y, & $a, & $b) : void
{
$a = $x->value;
$b = $y->value;
if ($b !== '0' && $x->scale > $y->scale) {
$b .= \str_repeat('0', $x->scale - $y->scale);
} elseif ($a !== '0' && $x->scale < $y->scale) {
$a .= \str_repeat('0', $y->scale - $x->scale);
}
} | [
"private",
"function",
"scaleValues",
"(",
"BigDecimal",
"$",
"x",
",",
"BigDecimal",
"$",
"y",
",",
"&",
"$",
"a",
",",
"&",
"$",
"b",
")",
":",
"void",
"{",
"$",
"a",
"=",
"$",
"x",
"->",
"value",
";",
"$",
"b",
"=",
"$",
"y",
"->",
"value"... | Puts the internal values of the given decimal numbers on the same scale.
@param BigDecimal $x The first decimal number.
@param BigDecimal $y The second decimal number.
@param string $a A variable to store the scaled integer value of $x.
@param string $b A variable to store the scaled integer value of $y.
@return void | [
"Puts",
"the",
"internal",
"values",
"of",
"the",
"given",
"decimal",
"numbers",
"on",
"the",
"same",
"scale",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L772-L782 |
brick/math | src/BigDecimal.php | BigDecimal.valueWithMinScale | private function valueWithMinScale(int $scale) : string
{
$value = $this->value;
if ($this->value !== '0' && $scale > $this->scale) {
$value .= \str_repeat('0', $scale - $this->scale);
}
return $value;
} | php | private function valueWithMinScale(int $scale) : string
{
$value = $this->value;
if ($this->value !== '0' && $scale > $this->scale) {
$value .= \str_repeat('0', $scale - $this->scale);
}
return $value;
} | [
"private",
"function",
"valueWithMinScale",
"(",
"int",
"$",
"scale",
")",
":",
"string",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"value",
";",
"if",
"(",
"$",
"this",
"->",
"value",
"!==",
"'0'",
"&&",
"$",
"scale",
">",
"$",
"this",
"->",
"sca... | @param int $scale
@return string | [
"@param",
"int",
"$scale"
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L789-L798 |
brick/math | src/BigDecimal.php | BigDecimal.getUnscaledValueWithLeadingZeros | private function getUnscaledValueWithLeadingZeros() : string
{
$value = $this->value;
$targetLength = $this->scale + 1;
$negative = ($value[0] === '-');
$length = \strlen($value);
if ($negative) {
$length--;
}
if ($length >= $targetLength) {
return $this->value;
}
if ($negative) {
$value = \substr($value, 1);
}
$value = \str_pad($value, $targetLength, '0', STR_PAD_LEFT);
if ($negative) {
$value = '-' . $value;
}
return $value;
} | php | private function getUnscaledValueWithLeadingZeros() : string
{
$value = $this->value;
$targetLength = $this->scale + 1;
$negative = ($value[0] === '-');
$length = \strlen($value);
if ($negative) {
$length--;
}
if ($length >= $targetLength) {
return $this->value;
}
if ($negative) {
$value = \substr($value, 1);
}
$value = \str_pad($value, $targetLength, '0', STR_PAD_LEFT);
if ($negative) {
$value = '-' . $value;
}
return $value;
} | [
"private",
"function",
"getUnscaledValueWithLeadingZeros",
"(",
")",
":",
"string",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"value",
";",
"$",
"targetLength",
"=",
"$",
"this",
"->",
"scale",
"+",
"1",
";",
"$",
"negative",
"=",
"(",
"$",
"value",
"... | Adds leading zeros if necessary to the unscaled value to represent the full decimal number.
@return string | [
"Adds",
"leading",
"zeros",
"if",
"necessary",
"to",
"the",
"unscaled",
"value",
"to",
"represent",
"the",
"full",
"decimal",
"number",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/BigDecimal.php#L805-L831 |
brick/math | src/Exception/NumberFormatException.php | NumberFormatException.charNotInAlphabet | public static function charNotInAlphabet(string $char) : self
{
$ord = \ord($char);
if ($ord < 32 || $ord > 126) {
$char = \strtoupper(\dechex($ord));
if ($ord < 10) {
$char = '0' . $char;
}
} else {
$char = '"' . $char . '"';
}
return new self(sprintf('Char %s is not a valid character in the given alphabet.', $char));
} | php | public static function charNotInAlphabet(string $char) : self
{
$ord = \ord($char);
if ($ord < 32 || $ord > 126) {
$char = \strtoupper(\dechex($ord));
if ($ord < 10) {
$char = '0' . $char;
}
} else {
$char = '"' . $char . '"';
}
return new self(sprintf('Char %s is not a valid character in the given alphabet.', $char));
} | [
"public",
"static",
"function",
"charNotInAlphabet",
"(",
"string",
"$",
"char",
")",
":",
"self",
"{",
"$",
"ord",
"=",
"\\",
"ord",
"(",
"$",
"char",
")",
";",
"if",
"(",
"$",
"ord",
"<",
"32",
"||",
"$",
"ord",
">",
"126",
")",
"{",
"$",
"ch... | @param string $char The failing character.
@return NumberFormatException | [
"@param",
"string",
"$char",
"The",
"failing",
"character",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Exception/NumberFormatException.php#L17-L32 |
brick/math | src/Internal/Calculator.php | Calculator.get | final public static function get() : Calculator
{
if (self::$instance === null) {
self::$instance = self::detect();
}
return self::$instance;
} | php | final public static function get() : Calculator
{
if (self::$instance === null) {
self::$instance = self::detect();
}
return self::$instance;
} | [
"final",
"public",
"static",
"function",
"get",
"(",
")",
":",
"Calculator",
"{",
"if",
"(",
"self",
"::",
"$",
"instance",
"===",
"null",
")",
"{",
"self",
"::",
"$",
"instance",
"=",
"self",
"::",
"detect",
"(",
")",
";",
"}",
"return",
"self",
"... | Returns the Calculator instance to use.
If none has been explicitly set, the fastest available implementation will be returned.
@return Calculator | [
"Returns",
"the",
"Calculator",
"instance",
"to",
"use",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator.php#L61-L68 |
brick/math | src/Internal/Calculator.php | Calculator.detect | private static function detect() : Calculator
{
if (\extension_loaded('gmp')) {
return new Calculator\GmpCalculator();
}
if (\extension_loaded('bcmath')) {
return new Calculator\BcMathCalculator();
}
return new Calculator\NativeCalculator();
} | php | private static function detect() : Calculator
{
if (\extension_loaded('gmp')) {
return new Calculator\GmpCalculator();
}
if (\extension_loaded('bcmath')) {
return new Calculator\BcMathCalculator();
}
return new Calculator\NativeCalculator();
} | [
"private",
"static",
"function",
"detect",
"(",
")",
":",
"Calculator",
"{",
"if",
"(",
"\\",
"extension_loaded",
"(",
"'gmp'",
")",
")",
"{",
"return",
"new",
"Calculator",
"\\",
"GmpCalculator",
"(",
")",
";",
"}",
"if",
"(",
"\\",
"extension_loaded",
... | Returns the fastest available Calculator implementation.
@codeCoverageIgnore
@return Calculator | [
"Returns",
"the",
"fastest",
"available",
"Calculator",
"implementation",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator.php#L77-L88 |
brick/math | src/Internal/Calculator.php | Calculator.init | final protected function init(string $a, string $b, & $aDig, & $bDig, & $aNeg, & $bNeg) : void
{
$aNeg = ($a[0] === '-');
$bNeg = ($b[0] === '-');
$aDig = $aNeg ? \substr($a, 1) : $a;
$bDig = $bNeg ? \substr($b, 1) : $b;
} | php | final protected function init(string $a, string $b, & $aDig, & $bDig, & $aNeg, & $bNeg) : void
{
$aNeg = ($a[0] === '-');
$bNeg = ($b[0] === '-');
$aDig = $aNeg ? \substr($a, 1) : $a;
$bDig = $bNeg ? \substr($b, 1) : $b;
} | [
"final",
"protected",
"function",
"init",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
",",
"&",
"$",
"aDig",
",",
"&",
"$",
"bDig",
",",
"&",
"$",
"aNeg",
",",
"&",
"$",
"bNeg",
")",
":",
"void",
"{",
"$",
"aNeg",
"=",
"(",
"$",
"a",
... | Extracts the digits and sign of the operands.
@param string $a The first operand.
@param string $b The second operand.
@param string $aDig A variable to store the digits of the first operand.
@param string $bDig A variable to store the digits of the second operand.
@param bool $aNeg A variable to store whether the first operand is negative.
@param bool $bNeg A variable to store whether the second operand is negative.
@return void | [
"Extracts",
"the",
"digits",
"and",
"sign",
"of",
"the",
"operands",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator.php#L102-L109 |
brick/math | src/Internal/Calculator.php | Calculator.cmp | final public function cmp(string $a, string $b) : int
{
$this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg);
if ($aNeg && ! $bNeg) {
return -1;
}
if ($bNeg && ! $aNeg) {
return 1;
}
$aLen = \strlen($aDig);
$bLen = \strlen($bDig);
if ($aLen < $bLen) {
$result = -1;
} elseif ($aLen > $bLen) {
$result = 1;
} else {
$result = $aDig <=> $bDig;
}
return $aNeg ? -$result : $result;
} | php | final public function cmp(string $a, string $b) : int
{
$this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg);
if ($aNeg && ! $bNeg) {
return -1;
}
if ($bNeg && ! $aNeg) {
return 1;
}
$aLen = \strlen($aDig);
$bLen = \strlen($bDig);
if ($aLen < $bLen) {
$result = -1;
} elseif ($aLen > $bLen) {
$result = 1;
} else {
$result = $aDig <=> $bDig;
}
return $aNeg ? -$result : $result;
} | [
"final",
"public",
"function",
"cmp",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"int",
"{",
"$",
"this",
"->",
"init",
"(",
"$",
"a",
",",
"$",
"b",
",",
"$",
"aDig",
",",
"$",
"bDig",
",",
"$",
"aNeg",
",",
"$",
"bNeg",
"... | Compares two numbers.
@param string $a The first number.
@param string $b The second number.
@return int [-1, 0, 1] If the first number is less than, equal to, or greater than the second number. | [
"Compares",
"two",
"numbers",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator.php#L151-L175 |
brick/math | src/Internal/Calculator.php | Calculator.gcd | public function gcd(string $a, string $b) : string
{
if ($a === '0') {
return $this->abs($b);
}
if ($b === '0') {
return $this->abs($a);
}
return $this->gcd($b, $this->divR($a, $b));
} | php | public function gcd(string $a, string $b) : string
{
if ($a === '0') {
return $this->abs($b);
}
if ($b === '0') {
return $this->abs($a);
}
return $this->gcd($b, $this->divR($a, $b));
} | [
"public",
"function",
"gcd",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"string",
"{",
"if",
"(",
"$",
"a",
"===",
"'0'",
")",
"{",
"return",
"$",
"this",
"->",
"abs",
"(",
"$",
"b",
")",
";",
"}",
"if",
"(",
"$",
"b",
"===... | Returns the greatest common divisor of the two numbers.
This method can be overridden by the concrete implementation if the underlying library
has built-in support for GCD calculations.
@param string $a The first number.
@param string $b The second number.
@return string The GCD, always positive, or zero if both arguments are zero. | [
"Returns",
"the",
"greatest",
"common",
"divisor",
"of",
"the",
"two",
"numbers",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator.php#L258-L269 |
brick/math | src/Internal/Calculator.php | Calculator.fromBase | public function fromBase(string $number, int $base) : string
{
return $this->fromArbitraryBase(\strtolower($number), self::ALPHABET, $base);
} | php | public function fromBase(string $number, int $base) : string
{
return $this->fromArbitraryBase(\strtolower($number), self::ALPHABET, $base);
} | [
"public",
"function",
"fromBase",
"(",
"string",
"$",
"number",
",",
"int",
"$",
"base",
")",
":",
"string",
"{",
"return",
"$",
"this",
"->",
"fromArbitraryBase",
"(",
"\\",
"strtolower",
"(",
"$",
"number",
")",
",",
"self",
"::",
"ALPHABET",
",",
"$... | Converts a number from an arbitrary base.
This method can be overridden by the concrete implementation if the underlying library
has built-in support for base conversion.
@param string $number The number, positive or zero, non-empty, case-insensitively validated for the given base.
@param int $base The base of the number, validated from 2 to 36.
@return string The converted number, following the Calculator conventions. | [
"Converts",
"a",
"number",
"from",
"an",
"arbitrary",
"base",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator.php#L294-L297 |
brick/math | src/Internal/Calculator.php | Calculator.toBase | public function toBase(string $number, int $base) : string
{
$negative = ($number[0] === '-');
if ($negative) {
$number = \substr($number, 1);
}
$number = $this->toArbitraryBase($number, self::ALPHABET, $base);
if ($negative) {
return '-' . $number;
}
return $number;
} | php | public function toBase(string $number, int $base) : string
{
$negative = ($number[0] === '-');
if ($negative) {
$number = \substr($number, 1);
}
$number = $this->toArbitraryBase($number, self::ALPHABET, $base);
if ($negative) {
return '-' . $number;
}
return $number;
} | [
"public",
"function",
"toBase",
"(",
"string",
"$",
"number",
",",
"int",
"$",
"base",
")",
":",
"string",
"{",
"$",
"negative",
"=",
"(",
"$",
"number",
"[",
"0",
"]",
"===",
"'-'",
")",
";",
"if",
"(",
"$",
"negative",
")",
"{",
"$",
"number",
... | Converts a number to an arbitrary base.
This method can be overridden by the concrete implementation if the underlying library
has built-in support for base conversion.
@param string $number The number to convert, following the Calculator conventions.
@param int $base The base to convert to, validated from 2 to 36.
@return string The converted number, lowercase. | [
"Converts",
"a",
"number",
"to",
"an",
"arbitrary",
"base",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator.php#L310-L325 |
brick/math | src/Internal/Calculator.php | Calculator.fromArbitraryBase | final public function fromArbitraryBase(string $number, string $alphabet, int $base) : string
{
// remove leading "zeros"
$number = \ltrim($number, $alphabet[0]);
if ($number === '') {
return '0';
}
// optimize for "one"
if ($number === $alphabet[1]) {
return '1';
}
$result = '0';
$power = '1';
$base = (string) $base;
for ($i = \strlen($number) - 1; $i >= 0; $i--) {
$index = \strpos($alphabet, $number[$i]);
if ($index !== 0) {
$result = $this->add($result, ($index === 1)
? $power
: $this->mul($power, (string) $index)
);
}
if ($i !== 0) {
$power = $this->mul($power, $base);
}
}
return $result;
} | php | final public function fromArbitraryBase(string $number, string $alphabet, int $base) : string
{
// remove leading "zeros"
$number = \ltrim($number, $alphabet[0]);
if ($number === '') {
return '0';
}
// optimize for "one"
if ($number === $alphabet[1]) {
return '1';
}
$result = '0';
$power = '1';
$base = (string) $base;
for ($i = \strlen($number) - 1; $i >= 0; $i--) {
$index = \strpos($alphabet, $number[$i]);
if ($index !== 0) {
$result = $this->add($result, ($index === 1)
? $power
: $this->mul($power, (string) $index)
);
}
if ($i !== 0) {
$power = $this->mul($power, $base);
}
}
return $result;
} | [
"final",
"public",
"function",
"fromArbitraryBase",
"(",
"string",
"$",
"number",
",",
"string",
"$",
"alphabet",
",",
"int",
"$",
"base",
")",
":",
"string",
"{",
"// remove leading \"zeros\"",
"$",
"number",
"=",
"\\",
"ltrim",
"(",
"$",
"number",
",",
"... | Converts a non-negative number in an arbitrary base using a custom alphabet, to base 10.
@param string $number The number to convert, validated as a non-empty string,
containing only chars in the given alphabet/base.
@param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.
@param int $base The base of the number, validated from 2 to alphabet length.
@return string The number in base 10, following the Calculator conventions. | [
"Converts",
"a",
"non",
"-",
"negative",
"number",
"in",
"an",
"arbitrary",
"base",
"using",
"a",
"custom",
"alphabet",
"to",
"base",
"10",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator.php#L337-L372 |
brick/math | src/Internal/Calculator.php | Calculator.toArbitraryBase | final public function toArbitraryBase(string $number, string $alphabet, int $base) : string
{
if ($number === '0') {
return $alphabet[0];
}
$base = (string) $base;
$result = '';
while ($number !== '0') {
[$number, $remainder] = $this->divQR($number, $base);
$remainder = (int) $remainder;
$result .= $alphabet[$remainder];
}
return \strrev($result);
} | php | final public function toArbitraryBase(string $number, string $alphabet, int $base) : string
{
if ($number === '0') {
return $alphabet[0];
}
$base = (string) $base;
$result = '';
while ($number !== '0') {
[$number, $remainder] = $this->divQR($number, $base);
$remainder = (int) $remainder;
$result .= $alphabet[$remainder];
}
return \strrev($result);
} | [
"final",
"public",
"function",
"toArbitraryBase",
"(",
"string",
"$",
"number",
",",
"string",
"$",
"alphabet",
",",
"int",
"$",
"base",
")",
":",
"string",
"{",
"if",
"(",
"$",
"number",
"===",
"'0'",
")",
"{",
"return",
"$",
"alphabet",
"[",
"0",
"... | Converts a non-negative number to an arbitrary base using a custom alphabet.
@param string $number The number to convert, positive or zero, following the Calculator conventions.
@param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.
@param int $base The base to convert to, validated from 2 to alphabet length.
@return string The converted number in the given alphabet. | [
"Converts",
"a",
"non",
"-",
"negative",
"number",
"to",
"an",
"arbitrary",
"base",
"using",
"a",
"custom",
"alphabet",
"."
] | train | https://github.com/brick/math/blob/5f1fff59b3413c9dafa67b9c4571c1df1898fac2/src/Internal/Calculator.php#L383-L400 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.