repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
rainlab/builder-plugin
classes/ControlLibrary.php
ControlLibrary.registerControl
public function registerControl($code, $name, $description, $controlGroup, $icon, $properties, $designTimeProviderClass) { if (!$designTimeProviderClass) { $designTimeProviderClass = self::DEFAULT_DESIGN_TIME_PROVIDER; } $this->controls[$code] = [ 'group' => $controlGroup, 'name' => $name, 'description' => $description, 'icon' => $icon, 'properties' => $properties, 'designTimeProvider' => $designTimeProviderClass ]; }
php
public function registerControl($code, $name, $description, $controlGroup, $icon, $properties, $designTimeProviderClass) { if (!$designTimeProviderClass) { $designTimeProviderClass = self::DEFAULT_DESIGN_TIME_PROVIDER; } $this->controls[$code] = [ 'group' => $controlGroup, 'name' => $name, 'description' => $description, 'icon' => $icon, 'properties' => $properties, 'designTimeProvider' => $designTimeProviderClass ]; }
[ "public", "function", "registerControl", "(", "$", "code", ",", "$", "name", ",", "$", "description", ",", "$", "controlGroup", ",", "$", "icon", ",", "$", "properties", ",", "$", "designTimeProviderClass", ")", "{", "if", "(", "!", "$", "designTimeProvide...
Registers a control. @param string $code Specifies the control code, for example "codeeditor". @param string $name Specifies the control name, for example "Code editor". @param string $description Specifies the control descritpion, can be empty. @param string|integer $controlGroup Specifies the control group. Control groups are used to create tabs in the Control Palette in Form Builder. The group could one of the ControlLibrary::GROUP_ constants or a string. @param string $icon Specifies the control icon for the Control Palette. @see http://octobercms.com/docs/ui/icon @param array $properties Specifies the control properties. The property definitions should be compatible with Inspector properties, similarly to the Component properties: http://octobercms.com/docs/plugin/components#component-properties Use the getStandardProperties() of the ControlLibrary to get the standard control properties. @param string $designTimeProviderClass Specifies the control design-time provider class name. The class should extend RainLab\Builder\Classes\ControlDesignTimeProviderBase. If the class is not provided, the default control design and design settings will be used.
[ "Registers", "a", "control", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/ControlLibrary.php#L95-L109
train
rainlab/builder-plugin
classes/DatabaseTableSchemaCreator.php
DatabaseTableSchemaCreator.formatOptions
protected function formatOptions($type, $options) { $result = MigrationColumnType::lengthToPrecisionAndScale($type, $options['length']); $result['unsigned'] = !!$options['unsigned']; $result['notnull'] = !$options['allow_null']; $result['autoincrement'] = !!$options['auto_increment']; $default = trim($options['default']); // Note - this code doesn't allow to set empty string as default. // But converting empty strings to NULLs is required for the further // work with Doctrine types. As an option - empty strings could be specified // as '' in the editor UI (table column editor). $result['default'] = $default === '' ? null : $default; return $result; }
php
protected function formatOptions($type, $options) { $result = MigrationColumnType::lengthToPrecisionAndScale($type, $options['length']); $result['unsigned'] = !!$options['unsigned']; $result['notnull'] = !$options['allow_null']; $result['autoincrement'] = !!$options['auto_increment']; $default = trim($options['default']); // Note - this code doesn't allow to set empty string as default. // But converting empty strings to NULLs is required for the further // work with Doctrine types. As an option - empty strings could be specified // as '' in the editor UI (table column editor). $result['default'] = $default === '' ? null : $default; return $result; }
[ "protected", "function", "formatOptions", "(", "$", "type", ",", "$", "options", ")", "{", "$", "result", "=", "MigrationColumnType", "::", "lengthToPrecisionAndScale", "(", "$", "type", ",", "$", "options", "[", "'length'", "]", ")", ";", "$", "result", "...
Converts column options to a format supported by Doctrine\DBAL\Schema\Column
[ "Converts", "column", "options", "to", "a", "format", "supported", "by", "Doctrine", "\\", "DBAL", "\\", "Schema", "\\", "Column" ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/DatabaseTableSchemaCreator.php#L47-L64
train
rainlab/builder-plugin
widgets/DefaultBehaviorDesignTimeProvider.php
DefaultBehaviorDesignTimeProvider.renderBehaviorBody
public function renderBehaviorBody($class, $properties, $controllerBuilder) { if (!array_key_exists($class, $this->defaultBehaviorClasses)) { return $this->renderUnknownBehavior($class, $properties); } $partial = $this->defaultBehaviorClasses[$class]; return $this->makePartial('behavior-'.$partial, [ 'properties'=>$properties, 'controllerBuilder' => $controllerBuilder ]); }
php
public function renderBehaviorBody($class, $properties, $controllerBuilder) { if (!array_key_exists($class, $this->defaultBehaviorClasses)) { return $this->renderUnknownBehavior($class, $properties); } $partial = $this->defaultBehaviorClasses[$class]; return $this->makePartial('behavior-'.$partial, [ 'properties'=>$properties, 'controllerBuilder' => $controllerBuilder ]); }
[ "public", "function", "renderBehaviorBody", "(", "$", "class", ",", "$", "properties", ",", "$", "controllerBuilder", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "class", ",", "$", "this", "->", "defaultBehaviorClasses", ")", ")", "{", "return", ...
Renders behaivor body. @param string $class Specifies the behavior class to render. @param array $properties Behavior property values. @param \RainLab\Builder\FormWidgets\ControllerBuilder $controllerBuilder ControllerBuilder widget instance. @return string Returns HTML markup string.
[ "Renders", "behaivor", "body", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/widgets/DefaultBehaviorDesignTimeProvider.php#L31-L43
train
rainlab/builder-plugin
widgets/DefaultBehaviorDesignTimeProvider.php
DefaultBehaviorDesignTimeProvider.getDefaultConfiguration
public function getDefaultConfiguration($class, $controllerModel, $controllerGenerator) { if (!array_key_exists($class, $this->defaultBehaviorClasses)) { throw new SystemException('Unknown behavior class: '.$class); } switch ($class) { case 'Backend\Behaviors\FormController' : return $this->getFormControllerDefaultConfiguration($controllerModel, $controllerGenerator); case 'Backend\Behaviors\ListController' : return $this->getListControllerDefaultConfiguration($controllerModel, $controllerGenerator); case 'Backend\Behaviors\ReorderController' : return $this->getReorderControllerDefaultConfiguration($controllerModel, $controllerGenerator); } }
php
public function getDefaultConfiguration($class, $controllerModel, $controllerGenerator) { if (!array_key_exists($class, $this->defaultBehaviorClasses)) { throw new SystemException('Unknown behavior class: '.$class); } switch ($class) { case 'Backend\Behaviors\FormController' : return $this->getFormControllerDefaultConfiguration($controllerModel, $controllerGenerator); case 'Backend\Behaviors\ListController' : return $this->getListControllerDefaultConfiguration($controllerModel, $controllerGenerator); case 'Backend\Behaviors\ReorderController' : return $this->getReorderControllerDefaultConfiguration($controllerModel, $controllerGenerator); } }
[ "public", "function", "getDefaultConfiguration", "(", "$", "class", ",", "$", "controllerModel", ",", "$", "controllerGenerator", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "class", ",", "$", "this", "->", "defaultBehaviorClasses", ")", ")", "{", ...
Returns default behavior configuration as an array. @param string $class Specifies the behavior class name. @param string $controllerModel Controller model. @param mixed $controllerGenerator Controller generator object. @return array Returns the behavior configuration array.
[ "Returns", "default", "behavior", "configuration", "as", "an", "array", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/widgets/DefaultBehaviorDesignTimeProvider.php#L52-L66
train
rainlab/builder-plugin
classes/DatabaseTableModel.php
DatabaseTableModel.load
public function load($name) { if (!self::tableExists($name)) { throw new SystemException(sprintf('The table with name %s doesn\'t exist', $name)); } $schema = self::getSchemaManager()->createSchema(); $this->name = $name; $this->tableInfo = $schema->getTable($this->name); $this->loadColumnsFromTableInfo(); $this->exists = true; }
php
public function load($name) { if (!self::tableExists($name)) { throw new SystemException(sprintf('The table with name %s doesn\'t exist', $name)); } $schema = self::getSchemaManager()->createSchema(); $this->name = $name; $this->tableInfo = $schema->getTable($this->name); $this->loadColumnsFromTableInfo(); $this->exists = true; }
[ "public", "function", "load", "(", "$", "name", ")", "{", "if", "(", "!", "self", "::", "tableExists", "(", "$", "name", ")", ")", "{", "throw", "new", "SystemException", "(", "sprintf", "(", "'The table with name %s doesn\\'t exist'", ",", "$", "name", ")...
Loads the table from the database. @param string $name Specifies the table name.
[ "Loads", "the", "table", "from", "the", "database", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/DatabaseTableModel.php#L74-L86
train
rainlab/builder-plugin
classes/ControllerBehaviorLibrary.php
ControllerBehaviorLibrary.registerBehavior
public function registerBehavior($class, $name, $description, $properties, $configFilePropertyName, $designTimeProviderClass, $configFileName, $viewTemplates = []) { if (!$designTimeProviderClass) { $designTimeProviderClass = self::DEFAULT_DESIGN_TIME_PROVIDER; } $this->behaviors[$class] = [ 'class' => $class, 'name' => Lang::get($name), 'description' => Lang::get($description), 'properties' => $properties, 'designTimeProvider' => $designTimeProviderClass, 'viewTemplates' => $viewTemplates, 'configFileName' => $configFileName, 'configPropertyName' => $configFilePropertyName ]; }
php
public function registerBehavior($class, $name, $description, $properties, $configFilePropertyName, $designTimeProviderClass, $configFileName, $viewTemplates = []) { if (!$designTimeProviderClass) { $designTimeProviderClass = self::DEFAULT_DESIGN_TIME_PROVIDER; } $this->behaviors[$class] = [ 'class' => $class, 'name' => Lang::get($name), 'description' => Lang::get($description), 'properties' => $properties, 'designTimeProvider' => $designTimeProviderClass, 'viewTemplates' => $viewTemplates, 'configFileName' => $configFileName, 'configPropertyName' => $configFilePropertyName ]; }
[ "public", "function", "registerBehavior", "(", "$", "class", ",", "$", "name", ",", "$", "description", ",", "$", "properties", ",", "$", "configFilePropertyName", ",", "$", "designTimeProviderClass", ",", "$", "configFileName", ",", "$", "viewTemplates", "=", ...
Registers a controller behavior. @param string $class Specifies the behavior class name. @param string $name Specifies the behavior name, for example "Form behavior". @param string $description Specifies the behavior description. @param array $properties Specifies the behavior properties. The property definitions should be compatible with Inspector properties, similarly to the Component properties: http://octobercms.com/docs/plugin/components#component-properties @param string $configFilePropertyName Specifies the name of the controller property that contains the configuration file name for the behavior. @param string $designTimeProviderClass Specifies the behavior design-time provider class name. The class should extend RainLab\Builder\Classes\BehaviorDesignTimeProviderBase. If the class is not provided, the default control design and design settings will be used. @param string $configFileName Default behavior configuration file name, for example config_form.yaml. @param array $viewTemplates An array of view templates that are required for the behavior. The templates are used when a new controller is created. The templates should be specified as paths to Twig files in the format ['~/plugins/author/plugin/behaviors/behaviorname/templates/view.htm.tpl'].
[ "Registers", "a", "controller", "behavior", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/ControllerBehaviorLibrary.php#L48-L64
train
rainlab/builder-plugin
classes/LanguageMixer.php
LanguageMixer.addStringsFromAnotherLanguage
public function addStringsFromAnotherLanguage($destContents, $srcArray) { // 1. Find array keys that exists in the source array and don't exist in the destination array // 2. Merge the arrays recursively // 3. To find which lines were added: // 3.1 get a YAML representation of the destination array // 3.2 walk through the missing paths obtained in step 1 and for each path: // 3.3 find its path and its corresponding line in the string from 3.1. $result = [ 'strings' => '', 'mismatch' => false, 'updatedLines' => [], ]; try { $destArray = Yaml::parse($destContents); } catch (Exception $ex) { throw new ApplicationException(sprintf('Cannot parse the YAML content: %s', $ex->getMessage())); } if (!$destArray) { $result['strings'] = $this->arrayToYaml($srcArray); return $result; } $mismatch = false; $missingPaths = $this->findMissingPaths($destArray, $srcArray, $mismatch); $mergedArray = self::arrayMergeRecursive($srcArray, $destArray); $destStrings = $this->arrayToYaml($mergedArray); $addedLines = $this->getAddedLines($destStrings, $missingPaths); $result['strings'] = $destStrings; $result['updatedLines'] = $addedLines['lines']; $result['mismatch'] = $mismatch || $addedLines['mismatch']; return $result; }
php
public function addStringsFromAnotherLanguage($destContents, $srcArray) { // 1. Find array keys that exists in the source array and don't exist in the destination array // 2. Merge the arrays recursively // 3. To find which lines were added: // 3.1 get a YAML representation of the destination array // 3.2 walk through the missing paths obtained in step 1 and for each path: // 3.3 find its path and its corresponding line in the string from 3.1. $result = [ 'strings' => '', 'mismatch' => false, 'updatedLines' => [], ]; try { $destArray = Yaml::parse($destContents); } catch (Exception $ex) { throw new ApplicationException(sprintf('Cannot parse the YAML content: %s', $ex->getMessage())); } if (!$destArray) { $result['strings'] = $this->arrayToYaml($srcArray); return $result; } $mismatch = false; $missingPaths = $this->findMissingPaths($destArray, $srcArray, $mismatch); $mergedArray = self::arrayMergeRecursive($srcArray, $destArray); $destStrings = $this->arrayToYaml($mergedArray); $addedLines = $this->getAddedLines($destStrings, $missingPaths); $result['strings'] = $destStrings; $result['updatedLines'] = $addedLines['lines']; $result['mismatch'] = $mismatch || $addedLines['mismatch']; return $result; }
[ "public", "function", "addStringsFromAnotherLanguage", "(", "$", "destContents", ",", "$", "srcArray", ")", "{", "// 1. Find array keys that exists in the source array and don't exist in the destination array", "// 2. Merge the arrays recursively", "// 3. To find which lines were added:", ...
Merges two localization languages and return merged YAML string and indexes of added lines.
[ "Merges", "two", "localization", "languages", "and", "return", "merged", "YAML", "string", "and", "indexes", "of", "added", "lines", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/LanguageMixer.php#L12-L52
train
rainlab/builder-plugin
classes/TableMigrationCodeGenerator.php
TableMigrationCodeGenerator.createOrUpdateTable
public function createOrUpdateTable($updatedTable, $existingTable, $newTableName) { $tableDiff = false; if ($existingTable !== null) { /* * The table already exists */ $comparator = new Comparator(); $tableDiff = $comparator->diffTable($existingTable, $updatedTable); if ($newTableName !== $existingTable->getName()) { if (!$tableDiff) { $tableDiff = new TableDiff($existingTable->getName()); } $tableDiff->newName = $newTableName; } } else { /* * The table doesn't exist */ $tableDiff = new TableDiff( $updatedTable->getName(), $updatedTable->getColumns(), [], // Changed columns [], // Removed columns $updatedTable->getIndexes() // Added indexes ); $tableDiff->fromTable = $updatedTable; } if (!$tableDiff) { return false; } if (!$this->tableHasNameOrColumnChanges($tableDiff) && !$this->tableHasPrimaryKeyChanges($tableDiff)) { return false; } return $this->generateCreateOrUpdateCode($tableDiff, !$existingTable, $updatedTable); }
php
public function createOrUpdateTable($updatedTable, $existingTable, $newTableName) { $tableDiff = false; if ($existingTable !== null) { /* * The table already exists */ $comparator = new Comparator(); $tableDiff = $comparator->diffTable($existingTable, $updatedTable); if ($newTableName !== $existingTable->getName()) { if (!$tableDiff) { $tableDiff = new TableDiff($existingTable->getName()); } $tableDiff->newName = $newTableName; } } else { /* * The table doesn't exist */ $tableDiff = new TableDiff( $updatedTable->getName(), $updatedTable->getColumns(), [], // Changed columns [], // Removed columns $updatedTable->getIndexes() // Added indexes ); $tableDiff->fromTable = $updatedTable; } if (!$tableDiff) { return false; } if (!$this->tableHasNameOrColumnChanges($tableDiff) && !$this->tableHasPrimaryKeyChanges($tableDiff)) { return false; } return $this->generateCreateOrUpdateCode($tableDiff, !$existingTable, $updatedTable); }
[ "public", "function", "createOrUpdateTable", "(", "$", "updatedTable", ",", "$", "existingTable", ",", "$", "newTableName", ")", "{", "$", "tableDiff", "=", "false", ";", "if", "(", "$", "existingTable", "!==", "null", ")", "{", "/*\n * The table alr...
Generates code for creating or updating a database table. @param \Doctrine\DBAL\Schema\Table $updatedTable Specifies the updated table schema. @param \Doctrine\DBAL\Schema\Table $existingTable Specifies the existing table schema, if applicable. @param string $newTableName An updated name of the theme. @return string|boolean Returns the migration up() and down() methods code. Returns false if there the table was not changed.
[ "Generates", "code", "for", "creating", "or", "updating", "a", "database", "table", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/TableMigrationCodeGenerator.php#L33-L76
train
rainlab/builder-plugin
classes/TableMigrationCodeGenerator.php
TableMigrationCodeGenerator.dropTable
public function dropTable($existingTable) { return $this->generateMigrationCode( $this->generateDropUpCode($existingTable), $this->generateDropDownCode($existingTable) ); }
php
public function dropTable($existingTable) { return $this->generateMigrationCode( $this->generateDropUpCode($existingTable), $this->generateDropDownCode($existingTable) ); }
[ "public", "function", "dropTable", "(", "$", "existingTable", ")", "{", "return", "$", "this", "->", "generateMigrationCode", "(", "$", "this", "->", "generateDropUpCode", "(", "$", "existingTable", ")", ",", "$", "this", "->", "generateDropDownCode", "(", "$"...
Generates code for dropping a database table. @param \Doctrine\DBAL\Schema\Table $existingTable Specifies the existing table schema. @return string Returns the migration up() and down() methods code.
[ "Generates", "code", "for", "dropping", "a", "database", "table", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/TableMigrationCodeGenerator.php#L104-L110
train
rainlab/builder-plugin
classes/MigrationColumnType.php
MigrationColumnType.toDoctrineTypeName
public static function toDoctrineTypeName($type) { $typeMap = self::getDoctrineTypeMap(); if (!array_key_exists($type, $typeMap)) { throw new SystemException(sprintf('Unknown column type: %s', $type)); } return $typeMap[$type]; }
php
public static function toDoctrineTypeName($type) { $typeMap = self::getDoctrineTypeMap(); if (!array_key_exists($type, $typeMap)) { throw new SystemException(sprintf('Unknown column type: %s', $type)); } return $typeMap[$type]; }
[ "public", "static", "function", "toDoctrineTypeName", "(", "$", "type", ")", "{", "$", "typeMap", "=", "self", "::", "getDoctrineTypeMap", "(", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "type", ",", "$", "typeMap", ")", ")", "{", "throw", ...
Converts a migration column type to a corresponding Doctrine mapping type name.
[ "Converts", "a", "migration", "column", "type", "to", "a", "corresponding", "Doctrine", "mapping", "type", "name", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/MigrationColumnType.php#L88-L97
train
rainlab/builder-plugin
classes/MigrationColumnType.php
MigrationColumnType.toMigrationMethodName
public static function toMigrationMethodName($type, $columnName) { $typeMap = self::getDoctrineTypeMap(); if (!in_array($type, $typeMap)) { throw new SystemException(sprintf('Unknown column type: %s', $type)); } // Some Doctrine types map to multiple migration types, for example // Doctrine boolean could be boolean and tinyInteger in migrations. // Some guessing could be required in this method. The method is not // 100% reliable. if ($type == DoctrineType::DATETIME) { // The datetime type maps to datetime and timestamp. Use the name // guessing as the only possible solution. if (in_array($columnName, ['created_at', 'updated_at', 'deleted_at', 'published_at', 'deleted_at'])) { return self::TYPE_TIMESTAMP; } return self::TYPE_DATETIME; } $typeMap = array_flip($typeMap); return $typeMap[$type]; }
php
public static function toMigrationMethodName($type, $columnName) { $typeMap = self::getDoctrineTypeMap(); if (!in_array($type, $typeMap)) { throw new SystemException(sprintf('Unknown column type: %s', $type)); } // Some Doctrine types map to multiple migration types, for example // Doctrine boolean could be boolean and tinyInteger in migrations. // Some guessing could be required in this method. The method is not // 100% reliable. if ($type == DoctrineType::DATETIME) { // The datetime type maps to datetime and timestamp. Use the name // guessing as the only possible solution. if (in_array($columnName, ['created_at', 'updated_at', 'deleted_at', 'published_at', 'deleted_at'])) { return self::TYPE_TIMESTAMP; } return self::TYPE_DATETIME; } $typeMap = array_flip($typeMap); return $typeMap[$type]; }
[ "public", "static", "function", "toMigrationMethodName", "(", "$", "type", ",", "$", "columnName", ")", "{", "$", "typeMap", "=", "self", "::", "getDoctrineTypeMap", "(", ")", ";", "if", "(", "!", "in_array", "(", "$", "type", ",", "$", "typeMap", ")", ...
Converts Doctrine mapping type name to a migration column method name
[ "Converts", "Doctrine", "mapping", "type", "name", "to", "a", "migration", "column", "method", "name" ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/MigrationColumnType.php#L102-L128
train
rainlab/builder-plugin
classes/MigrationColumnType.php
MigrationColumnType.validateLength
public static function validateLength($type, $value) { $value = trim($value); if (!strlen($value)) { return; } if (in_array($type, self::getDecimalTypes())) { if (!preg_match(self::REGEX_LENGTH_DOUBLE, $value)) { throw new ApplicationException(Lang::get('rainlab.builder::lang.database.error_table_decimal_length', [ 'type' => $type ])); } } else { if (!preg_match(self::REGEX_LENGTH_SINGLE, $value)) { throw new ApplicationException(Lang::get('rainlab.builder::lang.database.error_table_length', [ 'type' => $type ])); } } }
php
public static function validateLength($type, $value) { $value = trim($value); if (!strlen($value)) { return; } if (in_array($type, self::getDecimalTypes())) { if (!preg_match(self::REGEX_LENGTH_DOUBLE, $value)) { throw new ApplicationException(Lang::get('rainlab.builder::lang.database.error_table_decimal_length', [ 'type' => $type ])); } } else { if (!preg_match(self::REGEX_LENGTH_SINGLE, $value)) { throw new ApplicationException(Lang::get('rainlab.builder::lang.database.error_table_length', [ 'type' => $type ])); } } }
[ "public", "static", "function", "validateLength", "(", "$", "type", ",", "$", "value", ")", "{", "$", "value", "=", "trim", "(", "$", "value", ")", ";", "if", "(", "!", "strlen", "(", "$", "value", ")", ")", "{", "return", ";", "}", "if", "(", ...
Validates the column length parameter basing on the column type
[ "Validates", "the", "column", "length", "parameter", "basing", "on", "the", "column", "type" ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/MigrationColumnType.php#L133-L154
train
rainlab/builder-plugin
classes/MigrationColumnType.php
MigrationColumnType.lengthToPrecisionAndScale
public static function lengthToPrecisionAndScale($type, $length) { $length = trim($length); if (!strlen($length)) { return []; } $result = [ 'length' => null, 'precision' => null, 'scale' => null ]; if (in_array($type, self::getDecimalTypes())) { $matches = []; if (!preg_match(self::REGEX_LENGTH_DOUBLE, $length, $matches)) { throw new ApplicationException(Lang::get('rainlab.builder::lang.database.error_table_length', [ 'type' => $type ])); } $result['precision'] = $matches[1]; $result['scale'] = $matches[2]; return $result; } if (in_array($type, self::getIntegerTypes())) { if (!preg_match(self::REGEX_LENGTH_SINGLE, $length)) { throw new ApplicationException(Lang::get('rainlab.builder::lang.database.error_table_length', [ 'type' => $type ])); } $result['precision'] = $length; $result['scale'] = 0; return $result; } $result['length'] = $length; return $result; }
php
public static function lengthToPrecisionAndScale($type, $length) { $length = trim($length); if (!strlen($length)) { return []; } $result = [ 'length' => null, 'precision' => null, 'scale' => null ]; if (in_array($type, self::getDecimalTypes())) { $matches = []; if (!preg_match(self::REGEX_LENGTH_DOUBLE, $length, $matches)) { throw new ApplicationException(Lang::get('rainlab.builder::lang.database.error_table_length', [ 'type' => $type ])); } $result['precision'] = $matches[1]; $result['scale'] = $matches[2]; return $result; } if (in_array($type, self::getIntegerTypes())) { if (!preg_match(self::REGEX_LENGTH_SINGLE, $length)) { throw new ApplicationException(Lang::get('rainlab.builder::lang.database.error_table_length', [ 'type' => $type ])); } $result['precision'] = $length; $result['scale'] = 0; return $result; } $result['length'] = $length; return $result; }
[ "public", "static", "function", "lengthToPrecisionAndScale", "(", "$", "type", ",", "$", "length", ")", "{", "$", "length", "=", "trim", "(", "$", "length", ")", ";", "if", "(", "!", "strlen", "(", "$", "length", ")", ")", "{", "return", "[", "]", ...
Returns an array containing a column length, precision and scale, basing on the column type.
[ "Returns", "an", "array", "containing", "a", "column", "length", "precision", "and", "scale", "basing", "on", "the", "column", "type", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/MigrationColumnType.php#L159-L203
train
rainlab/builder-plugin
classes/MigrationColumnType.php
MigrationColumnType.doctrineLengthToMigrationLength
public static function doctrineLengthToMigrationLength($column) { $typeName = $column->getType()->getName(); $migrationTypeName = self::toMigrationMethodName($typeName, $column->getName()); if (in_array($migrationTypeName, self::getDecimalTypes())) { return $column->getPrecision().','.$column->getScale(); } if (in_array($migrationTypeName, self::getIntegerTypes())) { return $column->getPrecision(); } return $column->getLength(); }
php
public static function doctrineLengthToMigrationLength($column) { $typeName = $column->getType()->getName(); $migrationTypeName = self::toMigrationMethodName($typeName, $column->getName()); if (in_array($migrationTypeName, self::getDecimalTypes())) { return $column->getPrecision().','.$column->getScale(); } if (in_array($migrationTypeName, self::getIntegerTypes())) { return $column->getPrecision(); } return $column->getLength(); }
[ "public", "static", "function", "doctrineLengthToMigrationLength", "(", "$", "column", ")", "{", "$", "typeName", "=", "$", "column", "->", "getType", "(", ")", "->", "getName", "(", ")", ";", "$", "migrationTypeName", "=", "self", "::", "toMigrationMethodName...
Converts Doctrine length, precision and scale to migration-compatible length string @return string
[ "Converts", "Doctrine", "length", "precision", "and", "scale", "to", "migration", "-", "compatible", "length", "string" ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/MigrationColumnType.php#L209-L223
train
rainlab/builder-plugin
widgets/DefaultControlDesignTimeProvider.php
DefaultControlDesignTimeProvider.renderControlBody
public function renderControlBody($type, $properties, $formBuilder) { if (!in_array($type, $this->defaultControlsTypes)) { return $this->renderUnknownControl($type, $properties); } return $this->makePartial('control-'.$type, [ 'properties'=>$properties, 'formBuilder' => $formBuilder ]); }
php
public function renderControlBody($type, $properties, $formBuilder) { if (!in_array($type, $this->defaultControlsTypes)) { return $this->renderUnknownControl($type, $properties); } return $this->makePartial('control-'.$type, [ 'properties'=>$properties, 'formBuilder' => $formBuilder ]); }
[ "public", "function", "renderControlBody", "(", "$", "type", ",", "$", "properties", ",", "$", "formBuilder", ")", "{", "if", "(", "!", "in_array", "(", "$", "type", ",", "$", "this", "->", "defaultControlsTypes", ")", ")", "{", "return", "$", "this", ...
Renders control body. @param string $type Specifies the control type to render. @param array $properties Control property values. @param \RainLab\Builder\FormWidgets\FormBuilder $formBuilder FormBuilder widget instance. @return string Returns HTML markup string.
[ "Renders", "control", "body", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/widgets/DefaultControlDesignTimeProvider.php#L49-L59
train
rainlab/builder-plugin
widgets/DefaultControlDesignTimeProvider.php
DefaultControlDesignTimeProvider.renderControlStaticBody
public function renderControlStaticBody($type, $properties, $controlConfiguration, $formBuilder) { if (!in_array($type, $this->defaultControlsTypes)) { return null; } $partialName = 'control-static-'.$type; $partialPath = $this->getViewPath('_'.$partialName.'.htm'); if (!File::exists($partialPath)) { return null; } return $this->makePartial($partialName, [ 'properties'=>$properties, 'controlConfiguration' => $controlConfiguration, 'formBuilder' => $formBuilder ]); }
php
public function renderControlStaticBody($type, $properties, $controlConfiguration, $formBuilder) { if (!in_array($type, $this->defaultControlsTypes)) { return null; } $partialName = 'control-static-'.$type; $partialPath = $this->getViewPath('_'.$partialName.'.htm'); if (!File::exists($partialPath)) { return null; } return $this->makePartial($partialName, [ 'properties'=>$properties, 'controlConfiguration' => $controlConfiguration, 'formBuilder' => $formBuilder ]); }
[ "public", "function", "renderControlStaticBody", "(", "$", "type", ",", "$", "properties", ",", "$", "controlConfiguration", ",", "$", "formBuilder", ")", "{", "if", "(", "!", "in_array", "(", "$", "type", ",", "$", "this", "->", "defaultControlsTypes", ")",...
Renders control static body. The control static body is never updated with AJAX during the form editing. @param string $type Specifies the control type to render. @param array $properties Control property values preprocessed for the Inspector. @param array $controlConfiguration Raw control property values. @param \RainLab\Builder\FormWidgets\FormBuilder $formBuilder FormBuilder widget instance. @return string Returns HTML markup string.
[ "Renders", "control", "static", "body", ".", "The", "control", "static", "body", "is", "never", "updated", "with", "AJAX", "during", "the", "form", "editing", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/widgets/DefaultControlDesignTimeProvider.php#L70-L88
train
rainlab/builder-plugin
classes/MigrationFileParser.php
MigrationFileParser.extractMigrationInfoFromSource
public function extractMigrationInfoFromSource($fileContents) { $stream = new PhpSourceStream($fileContents); $result = []; while ($stream->forward()) { $tokenCode = $stream->getCurrentCode(); if ($tokenCode == T_NAMESPACE) { $namespace = $this->extractNamespace($stream); if ($namespace === null) { return null; } $result['namespace'] = $namespace; } if ($tokenCode == T_CLASS) { $className = $this->extractClassName($stream); if ($className === null) { return null; } $result['class'] = $className; } } if (!$result) { return null; } return $result; }
php
public function extractMigrationInfoFromSource($fileContents) { $stream = new PhpSourceStream($fileContents); $result = []; while ($stream->forward()) { $tokenCode = $stream->getCurrentCode(); if ($tokenCode == T_NAMESPACE) { $namespace = $this->extractNamespace($stream); if ($namespace === null) { return null; } $result['namespace'] = $namespace; } if ($tokenCode == T_CLASS) { $className = $this->extractClassName($stream); if ($className === null) { return null; } $result['class'] = $className; } } if (!$result) { return null; } return $result; }
[ "public", "function", "extractMigrationInfoFromSource", "(", "$", "fileContents", ")", "{", "$", "stream", "=", "new", "PhpSourceStream", "(", "$", "fileContents", ")", ";", "$", "result", "=", "[", "]", ";", "while", "(", "$", "stream", "->", "forward", "...
Returns the migration namespace and class name. @param string $fileContents Specifies the file contents. @return array|null Returns an array with keys 'class', 'namespace'. Returns null if the parsing fails.
[ "Returns", "the", "migration", "namespace", "and", "class", "name", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/MigrationFileParser.php#L17-L50
train
rainlab/builder-plugin
classes/PhpSourceStream.php
PhpSourceStream.setHead
public function setHead($head) { if ($head < 0) { return false; } if ($head > (count($this->tokens) - 1)) { return false; } $this->head = $head; return true; }
php
public function setHead($head) { if ($head < 0) { return false; } if ($head > (count($this->tokens) - 1)) { return false; } $this->head = $head; return true; }
[ "public", "function", "setHead", "(", "$", "head", ")", "{", "if", "(", "$", "head", "<", "0", ")", "{", "return", "false", ";", "}", "if", "(", "$", "head", ">", "(", "count", "(", "$", "this", "->", "tokens", ")", "-", "1", ")", ")", "{", ...
Updates the head position. @return boolean Returns true if the head was successfully updated. Returns false otherwise.
[ "Updates", "the", "head", "position", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/PhpSourceStream.php#L41-L53
train
rainlab/builder-plugin
classes/PhpSourceStream.php
PhpSourceStream.restoreBookmark
public function restoreBookmark() { $head = array_pop($this->headBookmarks); if ($head === null) { throw new SystemException("Can't restore PHP token stream bookmark - the bookmark doesn't exist"); } return $this->setHead($head); }
php
public function restoreBookmark() { $head = array_pop($this->headBookmarks); if ($head === null) { throw new SystemException("Can't restore PHP token stream bookmark - the bookmark doesn't exist"); } return $this->setHead($head); }
[ "public", "function", "restoreBookmark", "(", ")", "{", "$", "head", "=", "array_pop", "(", "$", "this", "->", "headBookmarks", ")", ";", "if", "(", "$", "head", "===", "null", ")", "{", "throw", "new", "SystemException", "(", "\"Can't restore PHP token stre...
Restores the head position from the last stored bookmark.
[ "Restores", "the", "head", "position", "from", "the", "last", "stored", "bookmark", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/PhpSourceStream.php#L66-L74
train
rainlab/builder-plugin
classes/PhpSourceStream.php
PhpSourceStream.getNext
public function getNext() { $nextIndex = $this->head + 1; if (!array_key_exists($nextIndex, $this->tokens)) { return null; } $this->head = $nextIndex; return $this->tokens[$nextIndex]; }
php
public function getNext() { $nextIndex = $this->head + 1; if (!array_key_exists($nextIndex, $this->tokens)) { return null; } $this->head = $nextIndex; return $this->tokens[$nextIndex]; }
[ "public", "function", "getNext", "(", ")", "{", "$", "nextIndex", "=", "$", "this", "->", "head", "+", "1", ";", "if", "(", "!", "array_key_exists", "(", "$", "nextIndex", ",", "$", "this", "->", "tokens", ")", ")", "{", "return", "null", ";", "}",...
Returns the next token and moves the head forward.
[ "Returns", "the", "next", "token", "and", "moves", "the", "head", "forward", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/PhpSourceStream.php#L124-L133
train
rainlab/builder-plugin
classes/PhpSourceStream.php
PhpSourceStream.getNextExpected
public function getNextExpected($expectedCode) { $token = $this->getNext(); if ($this->getCurrentCode() != $expectedCode) { return null; } return $token; }
php
public function getNextExpected($expectedCode) { $token = $this->getNext(); if ($this->getCurrentCode() != $expectedCode) { return null; } return $token; }
[ "public", "function", "getNextExpected", "(", "$", "expectedCode", ")", "{", "$", "token", "=", "$", "this", "->", "getNext", "(", ")", ";", "if", "(", "$", "this", "->", "getCurrentCode", "(", ")", "!=", "$", "expectedCode", ")", "{", "return", "null"...
Reads the next token, updates the head and and returns the token if it has the expected code. @param integer $expectedCode Specifies the code to expect. @return mixed Returns the token or null if the token code was not expected.
[ "Reads", "the", "next", "token", "updates", "the", "head", "and", "and", "returns", "the", "token", "if", "it", "has", "the", "expected", "code", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/PhpSourceStream.php#L140-L148
train
rainlab/builder-plugin
classes/PhpSourceStream.php
PhpSourceStream.getNextExpectedTerminated
public function getNextExpectedTerminated($expectedCodesOrValues, $terminationToken) { $buffer = null; if (!is_array($terminationToken)) { $terminationToken = [$terminationToken]; } while (($nextToken = $this->getNext()) !== null) { $code = $this->getCurrentCode(); $text = $this->getCurrentText(); if (in_array($code, $expectedCodesOrValues) || in_array($text, $expectedCodesOrValues)) { $buffer .= $text; continue; } if (in_array($code, $terminationToken)) { return $buffer; } if (in_array($text, $terminationToken)) { return $buffer; } // The token should be either expected or termination. // If something else is found, return null. return null; } return $buffer; }
php
public function getNextExpectedTerminated($expectedCodesOrValues, $terminationToken) { $buffer = null; if (!is_array($terminationToken)) { $terminationToken = [$terminationToken]; } while (($nextToken = $this->getNext()) !== null) { $code = $this->getCurrentCode(); $text = $this->getCurrentText(); if (in_array($code, $expectedCodesOrValues) || in_array($text, $expectedCodesOrValues)) { $buffer .= $text; continue; } if (in_array($code, $terminationToken)) { return $buffer; } if (in_array($text, $terminationToken)) { return $buffer; } // The token should be either expected or termination. // If something else is found, return null. return null; } return $buffer; }
[ "public", "function", "getNextExpectedTerminated", "(", "$", "expectedCodesOrValues", ",", "$", "terminationToken", ")", "{", "$", "buffer", "=", "null", ";", "if", "(", "!", "is_array", "(", "$", "terminationToken", ")", ")", "{", "$", "terminationToken", "="...
Reads expected tokens, until the termination token is found. If any unexpected token is found before the termination token, returns null. If the method succeeds, the head is positioned on the termination token. @param array $expectedCodesOrValues Specifies the expected codes or token values. @param integer|string|array $terminationToken Specifies the termination token text or code. The termination tokens could be specified as array. @return string|null Returns the tokens text or null
[ "Reads", "expected", "tokens", "until", "the", "termination", "token", "is", "found", ".", "If", "any", "unexpected", "token", "is", "found", "before", "the", "termination", "token", "returns", "null", ".", "If", "the", "method", "succeeds", "the", "head", "...
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/PhpSourceStream.php#L159-L190
train
rainlab/builder-plugin
classes/PhpSourceStream.php
PhpSourceStream.getTextToSemicolon
public function getTextToSemicolon() { $buffer = null; while (($nextToken = $this->getNext()) !== null) { if ($nextToken == ';') { return $buffer; } $buffer .= $this->getCurrentText(); } // The semicolon wasn't found. return null; }
php
public function getTextToSemicolon() { $buffer = null; while (($nextToken = $this->getNext()) !== null) { if ($nextToken == ';') { return $buffer; } $buffer .= $this->getCurrentText(); } // The semicolon wasn't found. return null; }
[ "public", "function", "getTextToSemicolon", "(", ")", "{", "$", "buffer", "=", "null", ";", "while", "(", "(", "$", "nextToken", "=", "$", "this", "->", "getNext", "(", ")", ")", "!==", "null", ")", "{", "if", "(", "$", "nextToken", "==", "';'", ")...
Returns the stream text from the head position to the next semicolon and updates the head. If the method succeeds, the head is positioned on the semicolon.
[ "Returns", "the", "stream", "text", "from", "the", "head", "position", "to", "the", "next", "semicolon", "and", "updates", "the", "head", ".", "If", "the", "method", "succeeds", "the", "head", "is", "positioned", "on", "the", "semicolon", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/PhpSourceStream.php#L217-L231
train
rainlab/builder-plugin
classes/ModelFileParser.php
ModelFileParser.extractModelInfoFromSource
public function extractModelInfoFromSource($fileContents) { $stream = new PhpSourceStream($fileContents); $result = []; while ($stream->forward()) { $tokenCode = $stream->getCurrentCode(); if ($tokenCode == T_NAMESPACE) { $namespace = $this->extractNamespace($stream); if ($namespace === null) { return null; } $result['namespace'] = $namespace; } if ($tokenCode == T_CLASS && !isset($result['class'])) { $className = $this->extractClassName($stream); if ($className === null) { return null; } $result['class'] = $className; } if ($tokenCode == T_PUBLIC || $tokenCode == T_PROTECTED) { $tableName = $this->extractTableName($stream); if ($tableName === false) { continue; } if ($tableName === null) { return null; } $result['table'] = $tableName; } } if (!$result) { return null; } return $result; }
php
public function extractModelInfoFromSource($fileContents) { $stream = new PhpSourceStream($fileContents); $result = []; while ($stream->forward()) { $tokenCode = $stream->getCurrentCode(); if ($tokenCode == T_NAMESPACE) { $namespace = $this->extractNamespace($stream); if ($namespace === null) { return null; } $result['namespace'] = $namespace; } if ($tokenCode == T_CLASS && !isset($result['class'])) { $className = $this->extractClassName($stream); if ($className === null) { return null; } $result['class'] = $className; } if ($tokenCode == T_PUBLIC || $tokenCode == T_PROTECTED) { $tableName = $this->extractTableName($stream); if ($tableName === false) { continue; } if ($tableName === null) { return null; } $result['table'] = $tableName; } } if (!$result) { return null; } return $result; }
[ "public", "function", "extractModelInfoFromSource", "(", "$", "fileContents", ")", "{", "$", "stream", "=", "new", "PhpSourceStream", "(", "$", "fileContents", ")", ";", "$", "result", "=", "[", "]", ";", "while", "(", "$", "stream", "->", "forward", "(", ...
Returns the model namespace, class name and table name. @param string $fileContents Specifies the file contents. @return array|null Returns an array with keys 'namespace', 'class' and 'table' Returns null if the parsing fails.
[ "Returns", "the", "model", "namespace", "class", "name", "and", "table", "name", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/ModelFileParser.php#L17-L63
train
rainlab/builder-plugin
classes/ModelFileParser.php
ModelFileParser.extractModelRelationsFromSource
public function extractModelRelationsFromSource($fileContents) { $result = []; $stream = new PhpSourceStream($fileContents); while ($stream->forward()) { $tokenCode = $stream->getCurrentCode(); if ($tokenCode == T_PUBLIC) { $relations = $this->extractRelations($stream); if ($relations === false) { continue; } } } if (!$result) { return null; } return $result; }
php
public function extractModelRelationsFromSource($fileContents) { $result = []; $stream = new PhpSourceStream($fileContents); while ($stream->forward()) { $tokenCode = $stream->getCurrentCode(); if ($tokenCode == T_PUBLIC) { $relations = $this->extractRelations($stream); if ($relations === false) { continue; } } } if (!$result) { return null; } return $result; }
[ "public", "function", "extractModelRelationsFromSource", "(", "$", "fileContents", ")", "{", "$", "result", "=", "[", "]", ";", "$", "stream", "=", "new", "PhpSourceStream", "(", "$", "fileContents", ")", ";", "while", "(", "$", "stream", "->", "forward", ...
Extracts names and types of model relations. @param string $fileContents Specifies the file contents. @return array|null Returns an array with keys matching the relation types and values containing relation names as array. Returns null if the parsing fails.
[ "Extracts", "names", "and", "types", "of", "model", "relations", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/ModelFileParser.php#L71-L93
train
rainlab/builder-plugin
classes/MigrationModel.php
MigrationModel.save
public function save($executeOnSave = true) { $this->validate(); if (!strlen($this->scriptFileName) || !$this->isNewModel()) { $this->assignFileName(); } $originalFileContents = $this->saveScriptFile(); try { $originalVersionData = $this->insertOrUpdateVersion(); } catch (Exception $ex) { // Remove the script file, but don't rollback // the version.yaml. $this->rollbackSaving(null, $originalFileContents); throw $ex; } try { if ($executeOnSave) { VersionManager::instance()->updatePlugin($this->getPluginCodeObj()->toCode(), $this->version); } } catch (Exception $ex) { // Remove the script file, and rollback // the version.yaml. $this->rollbackSaving($originalVersionData, $originalFileContents); throw $ex; } $this->originalVersion = $this->version; $this->exists = true; }
php
public function save($executeOnSave = true) { $this->validate(); if (!strlen($this->scriptFileName) || !$this->isNewModel()) { $this->assignFileName(); } $originalFileContents = $this->saveScriptFile(); try { $originalVersionData = $this->insertOrUpdateVersion(); } catch (Exception $ex) { // Remove the script file, but don't rollback // the version.yaml. $this->rollbackSaving(null, $originalFileContents); throw $ex; } try { if ($executeOnSave) { VersionManager::instance()->updatePlugin($this->getPluginCodeObj()->toCode(), $this->version); } } catch (Exception $ex) { // Remove the script file, and rollback // the version.yaml. $this->rollbackSaving($originalVersionData, $originalFileContents); throw $ex; } $this->originalVersion = $this->version; $this->exists = true; }
[ "public", "function", "save", "(", "$", "executeOnSave", "=", "true", ")", "{", "$", "this", "->", "validate", "(", ")", ";", "if", "(", "!", "strlen", "(", "$", "this", "->", "scriptFileName", ")", "||", "!", "$", "this", "->", "isNewModel", "(", ...
Saves the migration and applies all outstanding migrations for the plugin.
[ "Saves", "the", "migration", "and", "applies", "all", "outstanding", "migrations", "for", "the", "plugin", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/MigrationModel.php#L111-L146
train
rainlab/builder-plugin
classes/ModelYamlModel.php
ModelYamlModel.getDisplayName
public function getDisplayName($nameFallback) { $fileName = $this->fileName; if (substr($fileName, -5) == '.yaml') { $fileName = substr($fileName, 0, -5); } if (!strlen($fileName)) { $fileName = $nameFallback; } return $this->getModelClassName().'/'.$fileName; }
php
public function getDisplayName($nameFallback) { $fileName = $this->fileName; if (substr($fileName, -5) == '.yaml') { $fileName = substr($fileName, 0, -5); } if (!strlen($fileName)) { $fileName = $nameFallback; } return $this->getModelClassName().'/'.$fileName; }
[ "public", "function", "getDisplayName", "(", "$", "nameFallback", ")", "{", "$", "fileName", "=", "$", "this", "->", "fileName", ";", "if", "(", "substr", "(", "$", "fileName", ",", "-", "5", ")", "==", "'.yaml'", ")", "{", "$", "fileName", "=", "sub...
Returns a string suitable for displaying in the Builder UI tabs.
[ "Returns", "a", "string", "suitable", "for", "displaying", "in", "the", "Builder", "UI", "tabs", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/ModelYamlModel.php#L53-L66
train
rainlab/builder-plugin
classes/ModelYamlModel.php
ModelYamlModel.getFilePath
protected function getFilePath() { $fileName = trim($this->fileName); if (!strlen($fileName)) { throw new SystemException('The form model file name is not set.'); } $fileName = $this->addExtension($fileName); return $this->getPluginCodeObj()->toPluginDirectoryPath().'/models/'.strtolower($this->getModelClassName()).'/'.$fileName; }
php
protected function getFilePath() { $fileName = trim($this->fileName); if (!strlen($fileName)) { throw new SystemException('The form model file name is not set.'); } $fileName = $this->addExtension($fileName); return $this->getPluginCodeObj()->toPluginDirectoryPath().'/models/'.strtolower($this->getModelClassName()).'/'.$fileName; }
[ "protected", "function", "getFilePath", "(", ")", "{", "$", "fileName", "=", "trim", "(", "$", "this", "->", "fileName", ")", ";", "if", "(", "!", "strlen", "(", "$", "fileName", ")", ")", "{", "throw", "new", "SystemException", "(", "'The form model fil...
Returns a file path to save the model to. @return string Returns a path.
[ "Returns", "a", "file", "path", "to", "save", "the", "model", "to", "." ]
e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf
https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/ModelYamlModel.php#L183-L193
train
backup-manager/laravel
src/Laravel4ServiceProvider.php
Laravel4ServiceProvider.registerDatabaseProvider
private function registerDatabaseProvider() { $this->app->bind(\BackupManager\Databases\DatabaseProvider::class, function ($app) { $provider = new Databases\DatabaseProvider($this->getDatabaseConfig($app['config']['database.connections'])); $provider->add(new Databases\MysqlDatabase); $provider->add(new Databases\PostgresqlDatabase); return $provider; }); }
php
private function registerDatabaseProvider() { $this->app->bind(\BackupManager\Databases\DatabaseProvider::class, function ($app) { $provider = new Databases\DatabaseProvider($this->getDatabaseConfig($app['config']['database.connections'])); $provider->add(new Databases\MysqlDatabase); $provider->add(new Databases\PostgresqlDatabase); return $provider; }); }
[ "private", "function", "registerDatabaseProvider", "(", ")", "{", "$", "this", "->", "app", "->", "bind", "(", "\\", "BackupManager", "\\", "Databases", "\\", "DatabaseProvider", "::", "class", ",", "function", "(", "$", "app", ")", "{", "$", "provider", "...
Register the database provider. @return void
[ "Register", "the", "database", "provider", "." ]
27bbe5d0e497b5796b098acd8433a7afd8982b8f
https://github.com/backup-manager/laravel/blob/27bbe5d0e497b5796b098acd8433a7afd8982b8f/src/Laravel4ServiceProvider.php#L68-L75
train
backup-manager/laravel
src/Laravel4ServiceProvider.php
Laravel4ServiceProvider.registerCompressorProvider
private function registerCompressorProvider() { $this->app->bind(\BackupManager\Compressors\CompressorProvider::class, function () { $provider = new Compressors\CompressorProvider; $provider->add(new Compressors\GzipCompressor); $provider->add(new Compressors\NullCompressor); return $provider; }); }
php
private function registerCompressorProvider() { $this->app->bind(\BackupManager\Compressors\CompressorProvider::class, function () { $provider = new Compressors\CompressorProvider; $provider->add(new Compressors\GzipCompressor); $provider->add(new Compressors\NullCompressor); return $provider; }); }
[ "private", "function", "registerCompressorProvider", "(", ")", "{", "$", "this", "->", "app", "->", "bind", "(", "\\", "BackupManager", "\\", "Compressors", "\\", "CompressorProvider", "::", "class", ",", "function", "(", ")", "{", "$", "provider", "=", "new...
Register the compressor provider. @return void
[ "Register", "the", "compressor", "provider", "." ]
27bbe5d0e497b5796b098acd8433a7afd8982b8f
https://github.com/backup-manager/laravel/blob/27bbe5d0e497b5796b098acd8433a7afd8982b8f/src/Laravel4ServiceProvider.php#L82-L89
train
simplito/elliptic-php
lib/Curve/EdwardsCurve.php
EdwardsCurve.jpoint
public function jpoint($x, $y, $z, $t = null) { return $this->point($x, $y, $z, $t); }
php
public function jpoint($x, $y, $z, $t = null) { return $this->point($x, $y, $z, $t); }
[ "public", "function", "jpoint", "(", "$", "x", ",", "$", "y", ",", "$", "z", ",", "$", "t", "=", "null", ")", "{", "return", "$", "this", "->", "point", "(", "$", "x", ",", "$", "y", ",", "$", "z", ",", "$", "t", ")", ";", "}" ]
Just for compatibility with Short curve
[ "Just", "for", "compatibility", "with", "Short", "curve" ]
8860a7f0219f573388379ac9e68097c01c76c4d3
https://github.com/simplito/elliptic-php/blob/8860a7f0219f573388379ac9e68097c01c76c4d3/lib/Curve/EdwardsCurve.php#L55-L57
train
simplito/elliptic-php
lib/Utils.php
Utils.getNAF
public static function getNAF($num, $w) { $naf = array(); $ws = 1 << ($w + 1); $k = clone($num); while( $k->cmpn(1) >= 0 ) { if( !$k->isOdd() ) array_push($naf, 0); else { $mod = $k->andln($ws - 1); $z = $mod; if( $mod > (($ws >> 1) - 1)) $z = ($ws >> 1) - $mod; $k->isubn($z); array_push($naf, $z); } // Optimization, shift by word if possible $shift = (!$k->isZero() && $k->andln($ws - 1) === 0) ? ($w + 1) : 1; for($i = 1; $i < $shift; $i++) array_push($naf, 0); $k->iushrn($shift); } return $naf; }
php
public static function getNAF($num, $w) { $naf = array(); $ws = 1 << ($w + 1); $k = clone($num); while( $k->cmpn(1) >= 0 ) { if( !$k->isOdd() ) array_push($naf, 0); else { $mod = $k->andln($ws - 1); $z = $mod; if( $mod > (($ws >> 1) - 1)) $z = ($ws >> 1) - $mod; $k->isubn($z); array_push($naf, $z); } // Optimization, shift by word if possible $shift = (!$k->isZero() && $k->andln($ws - 1) === 0) ? ($w + 1) : 1; for($i = 1; $i < $shift; $i++) array_push($naf, 0); $k->iushrn($shift); } return $naf; }
[ "public", "static", "function", "getNAF", "(", "$", "num", ",", "$", "w", ")", "{", "$", "naf", "=", "array", "(", ")", ";", "$", "ws", "=", "1", "<<", "(", "$", "w", "+", "1", ")", ";", "$", "k", "=", "clone", "(", "$", "num", ")", ";", ...
Represent num in a w-NAF form
[ "Represent", "num", "in", "a", "w", "-", "NAF", "form" ]
8860a7f0219f573388379ac9e68097c01c76c4d3
https://github.com/simplito/elliptic-php/blob/8860a7f0219f573388379ac9e68097c01c76c4d3/lib/Utils.php#L61-L89
train
simplito/elliptic-php
lib/Utils.php
Utils.getJSF
public static function getJSF($k1, $k2) { $jsf = array( array(), array() ); $k1 = $k1->_clone(); $k2 = $k2->_clone(); $d1 = 0; $d2 = 0; while( $k1->cmpn(-$d1) > 0 || $k2->cmpn(-$d2) > 0 ) { // First phase $m14 = ($k1->andln(3) + $d1) & 3; $m24 = ($k2->andln(3) + $d2) & 3; if( $m14 === 3 ) $m14 = -1; if( $m24 === 3 ) $m24 = -1; $u1 = 0; if( ($m14 & 1) !== 0 ) { $m8 = ($k1->andln(7) + $d1) & 7; $u1 = ( ($m8 === 3 || $m8 === 5) && $m24 === 2 ) ? -$m14 : $m14; } array_push($jsf[0], $u1); $u2 = 0; if( ($m24 & 1) !== 0 ) { $m8 = ($k2->andln(7) + $d2) & 7; $u2 = ( ($m8 === 3 || $m8 === 5) && $m14 === 2 ) ? -$m24 : $m24; } array_push($jsf[1], $u2); // Second phase if( (2 * $d1) === ($u1 + 1) ) $d1 = 1 - $d1; if( (2 * $d2) === ($u2 + 1) ) $d2 = 1 - $d2; $k1->iushrn(1); $k2->iushrn(1); } return $jsf; }
php
public static function getJSF($k1, $k2) { $jsf = array( array(), array() ); $k1 = $k1->_clone(); $k2 = $k2->_clone(); $d1 = 0; $d2 = 0; while( $k1->cmpn(-$d1) > 0 || $k2->cmpn(-$d2) > 0 ) { // First phase $m14 = ($k1->andln(3) + $d1) & 3; $m24 = ($k2->andln(3) + $d2) & 3; if( $m14 === 3 ) $m14 = -1; if( $m24 === 3 ) $m24 = -1; $u1 = 0; if( ($m14 & 1) !== 0 ) { $m8 = ($k1->andln(7) + $d1) & 7; $u1 = ( ($m8 === 3 || $m8 === 5) && $m24 === 2 ) ? -$m14 : $m14; } array_push($jsf[0], $u1); $u2 = 0; if( ($m24 & 1) !== 0 ) { $m8 = ($k2->andln(7) + $d2) & 7; $u2 = ( ($m8 === 3 || $m8 === 5) && $m14 === 2 ) ? -$m24 : $m24; } array_push($jsf[1], $u2); // Second phase if( (2 * $d1) === ($u1 + 1) ) $d1 = 1 - $d1; if( (2 * $d2) === ($u2 + 1) ) $d2 = 1 - $d2; $k1->iushrn(1); $k2->iushrn(1); } return $jsf; }
[ "public", "static", "function", "getJSF", "(", "$", "k1", ",", "$", "k2", ")", "{", "$", "jsf", "=", "array", "(", "array", "(", ")", ",", "array", "(", ")", ")", ";", "$", "k1", "=", "$", "k1", "->", "_clone", "(", ")", ";", "$", "k2", "="...
Represent k1, k2 in a Joint Sparse Form
[ "Represent", "k1", "k2", "in", "a", "Joint", "Sparse", "Form" ]
8860a7f0219f573388379ac9e68097c01c76c4d3
https://github.com/simplito/elliptic-php/blob/8860a7f0219f573388379ac9e68097c01c76c4d3/lib/Utils.php#L92-L136
train
WhichBrowser/Parser-PHP
src/Model/Main.php
Main.isX
private function isX() { $arguments = func_get_args(); $x = $arguments[0]; if (count($arguments) < 2) { return false; } if (empty($this->$x->name)) { return false; } if ($this->$x->name != $arguments[1]) { return false; } if (count($arguments) >= 4) { if (empty($this->$x->version)) { return false; } if (!$this->$x->version->is($arguments[2], $arguments[3])) { return false; } } return true; }
php
private function isX() { $arguments = func_get_args(); $x = $arguments[0]; if (count($arguments) < 2) { return false; } if (empty($this->$x->name)) { return false; } if ($this->$x->name != $arguments[1]) { return false; } if (count($arguments) >= 4) { if (empty($this->$x->version)) { return false; } if (!$this->$x->version->is($arguments[2], $arguments[3])) { return false; } } return true; }
[ "private", "function", "isX", "(", ")", "{", "$", "arguments", "=", "func_get_args", "(", ")", ";", "$", "x", "=", "$", "arguments", "[", "0", "]", ";", "if", "(", "count", "(", "$", "arguments", ")", "<", "2", ")", "{", "return", "false", ";", ...
Check the name of a property and optionally is a specific version @internal @param string The name of the property, such as 'browser', 'engine' or 'os' @param string The name of the browser that is checked @param string Optional, the operator, must be <, <=, =, >= or > @param mixed Optional, the value, can be an integer, float or string with a version number @return boolean
[ "Check", "the", "name", "of", "a", "property", "and", "optionally", "is", "a", "specific", "version" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Main.php#L69-L97
train
WhichBrowser/Parser-PHP
src/Model/Main.php
Main.isDetected
public function isDetected() { return $this->browser->isDetected() || $this->os->isDetected() || $this->engine->isDetected() || $this->device->isDetected(); }
php
public function isDetected() { return $this->browser->isDetected() || $this->os->isDetected() || $this->engine->isDetected() || $this->device->isDetected(); }
[ "public", "function", "isDetected", "(", ")", "{", "return", "$", "this", "->", "browser", "->", "isDetected", "(", ")", "||", "$", "this", "->", "os", "->", "isDetected", "(", ")", "||", "$", "this", "->", "engine", "->", "isDetected", "(", ")", "||...
Check if a browser was detected @return boolean
[ "Check", "if", "a", "browser", "was", "detected" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Main.php#L229-L232
train
WhichBrowser/Parser-PHP
src/Model/Main.php
Main.toString
public function toString() { $prefix = $this->camouflage ? 'an unknown browser that imitates ' : ''; $browser = $this->browser->toString(); $os = $this->os->toString(); $engine = $this->engine->toString(); $device = $this->device->toString(); if (empty($device) && empty($os) && $this->device->type == 'television') { $device = 'television'; } if (empty($device) && $this->device->type == 'emulator') { $device = 'emulator'; } if (!empty($browser) && !empty($os) && !empty($device)) { return $prefix . $browser . ' on ' . $this->a($device) . ' running ' . $os; } if (!empty($browser) && empty($os) && !empty($device)) { return $prefix . $browser . ' on ' . $this->a($device); } if (!empty($browser) && !empty($os) && empty($device)) { return $prefix . $browser . ' on ' . $os; } if (empty($browser) && !empty($os) && !empty($device)) { return $prefix . $this->a($device) . ' running ' . $os; } if (!empty($browser) && empty($os) && empty($device)) { return $prefix . $browser; } if (empty($browser) && empty($os) && !empty($device)) { return $prefix . $this->a($device); } if ($this->device->type == 'desktop' && !empty($os) && !empty($engine) && empty($device)) { return 'an unknown browser based on ' . $engine . ' running on ' . $os; } if ($this->browser->stock && !empty($os) && empty($device)) { return $os; } if ($this->browser->stock && !empty($engine) && empty($device)) { return 'an unknown browser based on ' . $engine; } if ($this->device->type == 'bot') { return 'an unknown bot'; } return 'an unknown browser'; }
php
public function toString() { $prefix = $this->camouflage ? 'an unknown browser that imitates ' : ''; $browser = $this->browser->toString(); $os = $this->os->toString(); $engine = $this->engine->toString(); $device = $this->device->toString(); if (empty($device) && empty($os) && $this->device->type == 'television') { $device = 'television'; } if (empty($device) && $this->device->type == 'emulator') { $device = 'emulator'; } if (!empty($browser) && !empty($os) && !empty($device)) { return $prefix . $browser . ' on ' . $this->a($device) . ' running ' . $os; } if (!empty($browser) && empty($os) && !empty($device)) { return $prefix . $browser . ' on ' . $this->a($device); } if (!empty($browser) && !empty($os) && empty($device)) { return $prefix . $browser . ' on ' . $os; } if (empty($browser) && !empty($os) && !empty($device)) { return $prefix . $this->a($device) . ' running ' . $os; } if (!empty($browser) && empty($os) && empty($device)) { return $prefix . $browser; } if (empty($browser) && empty($os) && !empty($device)) { return $prefix . $this->a($device); } if ($this->device->type == 'desktop' && !empty($os) && !empty($engine) && empty($device)) { return 'an unknown browser based on ' . $engine . ' running on ' . $os; } if ($this->browser->stock && !empty($os) && empty($device)) { return $os; } if ($this->browser->stock && !empty($engine) && empty($device)) { return 'an unknown browser based on ' . $engine; } if ($this->device->type == 'bot') { return 'an unknown bot'; } return 'an unknown browser'; }
[ "public", "function", "toString", "(", ")", "{", "$", "prefix", "=", "$", "this", "->", "camouflage", "?", "'an unknown browser that imitates '", ":", "''", ";", "$", "browser", "=", "$", "this", "->", "browser", "->", "toString", "(", ")", ";", "$", "os...
Get a human readable string of the whole browser identification @return string
[ "Get", "a", "human", "readable", "string", "of", "the", "whole", "browser", "identification" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Main.php#L257-L316
train
WhichBrowser/Parser-PHP
src/Model/Device.php
Device.identifyModel
public function identifyModel($pattern, $subject, $defaults = []) { if (preg_match($pattern, $subject, $match)) { $this->manufacturer = !empty($defaults['manufacturer']) ? $defaults['manufacturer'] : null; $this->model = Data\DeviceModels::cleanup($match[1]); $this->identifier = preg_replace('/ (Mozilla|Opera|Obigo|AU.Browser|UP.Browser|Build|Java|PPC|AU-MIC.*)$/iu', '', $match[0]); $this->identifier = preg_replace('/_(TD|GPRS|LTE|BLEU|CMCC|CUCC)$/iu', '', $match[0]); if (isset($defaults['model'])) { if (is_callable($defaults['model'])) { $this->model = call_user_func($defaults['model'], $this->model); } else { $this->model = $defaults['model']; } } $this->generic = false; $this->identified |= Constants\Id::PATTERN; if (!empty($defaults['carrier'])) { $this->carrier = $defaults['carrier']; } if (!empty($defaults['type'])) { $this->type = $defaults['type']; } } }
php
public function identifyModel($pattern, $subject, $defaults = []) { if (preg_match($pattern, $subject, $match)) { $this->manufacturer = !empty($defaults['manufacturer']) ? $defaults['manufacturer'] : null; $this->model = Data\DeviceModels::cleanup($match[1]); $this->identifier = preg_replace('/ (Mozilla|Opera|Obigo|AU.Browser|UP.Browser|Build|Java|PPC|AU-MIC.*)$/iu', '', $match[0]); $this->identifier = preg_replace('/_(TD|GPRS|LTE|BLEU|CMCC|CUCC)$/iu', '', $match[0]); if (isset($defaults['model'])) { if (is_callable($defaults['model'])) { $this->model = call_user_func($defaults['model'], $this->model); } else { $this->model = $defaults['model']; } } $this->generic = false; $this->identified |= Constants\Id::PATTERN; if (!empty($defaults['carrier'])) { $this->carrier = $defaults['carrier']; } if (!empty($defaults['type'])) { $this->type = $defaults['type']; } } }
[ "public", "function", "identifyModel", "(", "$", "pattern", ",", "$", "subject", ",", "$", "defaults", "=", "[", "]", ")", "{", "if", "(", "preg_match", "(", "$", "pattern", ",", "$", "subject", ",", "$", "match", ")", ")", "{", "$", "this", "->", ...
Identify the manufacturer and model based on a pattern @param string $pattern The regular expression that defines the group that matches the model @param string $subject The string the regular expression is matched with @param array|null $defaults An optional array of properties to set together @return string
[ "Identify", "the", "manufacturer", "and", "model", "based", "on", "a", "pattern" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Device.php#L84-L111
train
WhichBrowser/Parser-PHP
src/Model/Device.php
Device.setIdentification
public function setIdentification($properties) { $this->reset($properties); if (!empty($this->model)) { $this->generic = false; } $this->identified |= Constants\Id::MATCH_UA; }
php
public function setIdentification($properties) { $this->reset($properties); if (!empty($this->model)) { $this->generic = false; } $this->identified |= Constants\Id::MATCH_UA; }
[ "public", "function", "setIdentification", "(", "$", "properties", ")", "{", "$", "this", "->", "reset", "(", "$", "properties", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "model", ")", ")", "{", "$", "this", "->", "generic", "=", "...
Declare an positive identification @param array $properties An array, the key of an element determines the name of the property @return string
[ "Declare", "an", "positive", "identification" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Device.php#L122-L131
train
WhichBrowser/Parser-PHP
src/Model/Device.php
Device.getModel
public function getModel() { if ($this->identified) { return trim((!empty($this->model) ? $this->model . ' ' : '') . (!empty($this->series) ? $this->series : '')); } return !empty($this->model) ? $this->model : ''; }
php
public function getModel() { if ($this->identified) { return trim((!empty($this->model) ? $this->model . ' ' : '') . (!empty($this->series) ? $this->series : '')); } return !empty($this->model) ? $this->model : ''; }
[ "public", "function", "getModel", "(", ")", "{", "if", "(", "$", "this", "->", "identified", ")", "{", "return", "trim", "(", "(", "!", "empty", "(", "$", "this", "->", "model", ")", "?", "$", "this", "->", "model", ".", "' '", ":", "''", ")", ...
Get the name of the model in a human readable format @return string
[ "Get", "the", "name", "of", "the", "model", "in", "a", "human", "readable", "format" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Device.php#L164-L171
train
WhichBrowser/Parser-PHP
src/Model/Device.php
Device.toString
public function toString() { if ($this->hidden) { return ''; } if ($this->identified) { $model = $this->getModel(); $manufacturer = $this->getManufacturer(); if ($manufacturer != '' && strpos($model, $manufacturer) === 0) { $manufacturer = ''; } return trim($manufacturer . ' ' . $model); } return !empty($this->model) ? 'unrecognized device (' . $this->model . ')' : ''; }
php
public function toString() { if ($this->hidden) { return ''; } if ($this->identified) { $model = $this->getModel(); $manufacturer = $this->getManufacturer(); if ($manufacturer != '' && strpos($model, $manufacturer) === 0) { $manufacturer = ''; } return trim($manufacturer . ' ' . $model); } return !empty($this->model) ? 'unrecognized device (' . $this->model . ')' : ''; }
[ "public", "function", "toString", "(", ")", "{", "if", "(", "$", "this", "->", "hidden", ")", "{", "return", "''", ";", "}", "if", "(", "$", "this", "->", "identified", ")", "{", "$", "model", "=", "$", "this", "->", "getModel", "(", ")", ";", ...
Get the combined name of the manufacturer and model in a human readable format @return string
[ "Get", "the", "combined", "name", "of", "the", "manufacturer", "and", "model", "in", "a", "human", "readable", "format" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Device.php#L180-L198
train
WhichBrowser/Parser-PHP
src/Model/Device.php
Device.isDetected
public function isDetected() { return !empty($this->type) || !empty($this->model) || !empty($this->manufacturer); }
php
public function isDetected() { return !empty($this->type) || !empty($this->model) || !empty($this->manufacturer); }
[ "public", "function", "isDetected", "(", ")", "{", "return", "!", "empty", "(", "$", "this", "->", "type", ")", "||", "!", "empty", "(", "$", "this", "->", "model", ")", "||", "!", "empty", "(", "$", "this", "->", "manufacturer", ")", ";", "}" ]
Check if device information is detected @return boolean
[ "Check", "if", "device", "information", "is", "detected" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Device.php#L207-L210
train
WhichBrowser/Parser-PHP
src/Model/Os.php
Os.isFamily
public function isFamily($name) { if ($this->getName() == $name) { return true; } if (isset($this->family)) { if ($this->family->getName() == $name) { return true; } } return false; }
php
public function isFamily($name) { if ($this->getName() == $name) { return true; } if (isset($this->family)) { if ($this->family->getName() == $name) { return true; } } return false; }
[ "public", "function", "isFamily", "(", "$", "name", ")", "{", "if", "(", "$", "this", "->", "getName", "(", ")", "==", "$", "name", ")", "{", "return", "true", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "family", ")", ")", "{", "if",...
Is the operating from the specified family @param string $name The name of the family @return boolean
[ "Is", "the", "operating", "from", "the", "specified", "family" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Os.php#L68-L81
train
WhichBrowser/Parser-PHP
src/Parser.php
Parser.analyse
public function analyse($headers, $options = []) { $o = $options; if (is_string($headers)) { $h = [ 'User-Agent' => $headers ]; } else { if (isset($headers['headers'])) { $h = $headers['headers']; unset($headers['headers']); $o = array_merge($headers, $options); } else { $h = $headers; } } if ($this->analyseWithCache($h, $o)) { return; } $analyser = new Analyser($h, $o); $analyser->setdata($this); $analyser->analyse(); }
php
public function analyse($headers, $options = []) { $o = $options; if (is_string($headers)) { $h = [ 'User-Agent' => $headers ]; } else { if (isset($headers['headers'])) { $h = $headers['headers']; unset($headers['headers']); $o = array_merge($headers, $options); } else { $h = $headers; } } if ($this->analyseWithCache($h, $o)) { return; } $analyser = new Analyser($h, $o); $analyser->setdata($this); $analyser->analyse(); }
[ "public", "function", "analyse", "(", "$", "headers", ",", "$", "options", "=", "[", "]", ")", "{", "$", "o", "=", "$", "options", ";", "if", "(", "is_string", "(", "$", "headers", ")", ")", "{", "$", "h", "=", "[", "'User-Agent'", "=>", "$", "...
Analyse the provided headers or User-Agent string @param array|string $headers An array with all of the headers or a string with just the User-Agent header
[ "Analyse", "the", "provided", "headers", "or", "User", "-", "Agent", "string" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Parser.php#L33-L57
train
WhichBrowser/Parser-PHP
src/Cache.php
Cache.applyCachedData
private function applyCachedData($data) { foreach ($data as $key => $value) { $this->$key = $value; } $this->cached = true; }
php
private function applyCachedData($data) { foreach ($data as $key => $value) { $this->$key = $value; } $this->cached = true; }
[ "private", "function", "applyCachedData", "(", "$", "data", ")", "{", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "$", "key", "=", "$", "value", ";", "}", "$", "this", "->", "cached", "=", "true...
Apply cached data to the main Parser object @internal @param array $data An array with a key for every property it needs to apply
[ "Apply", "cached", "data", "to", "the", "main", "Parser", "object" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Cache.php#L41-L48
train
WhichBrowser/Parser-PHP
src/Cache.php
Cache.retrieveCachedData
private function retrieveCachedData() { return [ 'browser' => $this->browser, 'engine' => $this->engine, 'os' => $this->os, 'device' => $this->device, 'camouflage' => $this->camouflage, 'features' => $this->features ]; }
php
private function retrieveCachedData() { return [ 'browser' => $this->browser, 'engine' => $this->engine, 'os' => $this->os, 'device' => $this->device, 'camouflage' => $this->camouflage, 'features' => $this->features ]; }
[ "private", "function", "retrieveCachedData", "(", ")", "{", "return", "[", "'browser'", "=>", "$", "this", "->", "browser", ",", "'engine'", "=>", "$", "this", "->", "engine", ",", "'os'", "=>", "$", "this", "->", "os", ",", "'device'", "=>", "$", "thi...
Retrieve the data that can be cached from the main Parser object @internal @return array An array with a key for every property that will be cached
[ "Retrieve", "the", "data", "that", "can", "be", "cached", "from", "the", "main", "Parser", "object" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Cache.php#L59-L69
train
WhichBrowser/Parser-PHP
src/Cache.php
Cache.analyseWithCache
private function analyseWithCache($headers, $options = []) { if (isset($options['cache'])) { if (isset($options['cacheExpires'])) { $this->setCache($options['cache'], $options['cacheExpires']); } else { $this->setCache($options['cache']); } } if ($this->cache instanceof CacheItemPoolInterface) { $item = $this->cache->getItem('whichbrowser_' . md5(serialize($headers))); if ($item->isHit()) { $this->applyCachedData($item->get()); } else { $analyser = new Analyser($headers, $options); $analyser->setdata($this); $analyser->analyse(); $item->set($this->retrieveCachedData()); $item->expiresAfter($this->expires); $this->cache->save($item); } return true; } }
php
private function analyseWithCache($headers, $options = []) { if (isset($options['cache'])) { if (isset($options['cacheExpires'])) { $this->setCache($options['cache'], $options['cacheExpires']); } else { $this->setCache($options['cache']); } } if ($this->cache instanceof CacheItemPoolInterface) { $item = $this->cache->getItem('whichbrowser_' . md5(serialize($headers))); if ($item->isHit()) { $this->applyCachedData($item->get()); } else { $analyser = new Analyser($headers, $options); $analyser->setdata($this); $analyser->analyse(); $item->set($this->retrieveCachedData()); $item->expiresAfter($this->expires); $this->cache->save($item); } return true; } }
[ "private", "function", "analyseWithCache", "(", "$", "headers", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "options", "[", "'cache'", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "options", "[", "'cacheExpires'",...
Retrieve the result from the cache, or analyse and store in the cache @internal @param array|string $headers An array with all of the headers or a string with just the User-Agent header @return boolean did we actually retrieve or analyse results
[ "Retrieve", "the", "result", "from", "the", "cache", "or", "analyse", "and", "store", "in", "the", "cache" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Cache.php#L82-L109
train
WhichBrowser/Parser-PHP
src/Model/Primitive/NameVersion.php
NameVersion.identifyVersion
public function identifyVersion($pattern, $subject, $defaults = []) { if (preg_match($pattern, $subject, $match)) { $version = $match[1]; if (isset($defaults['type'])) { switch ($defaults['type']) { case 'underscore': $version = str_replace('_', '.', $version); break; case 'legacy': $version = preg_replace("/([0-9])([0-9])/", '$1.$2', $version); break; } } $this->version = new Version(array_merge($defaults, [ 'value' => $version ])); } }
php
public function identifyVersion($pattern, $subject, $defaults = []) { if (preg_match($pattern, $subject, $match)) { $version = $match[1]; if (isset($defaults['type'])) { switch ($defaults['type']) { case 'underscore': $version = str_replace('_', '.', $version); break; case 'legacy': $version = preg_replace("/([0-9])([0-9])/", '$1.$2', $version); break; } } $this->version = new Version(array_merge($defaults, [ 'value' => $version ])); } }
[ "public", "function", "identifyVersion", "(", "$", "pattern", ",", "$", "subject", ",", "$", "defaults", "=", "[", "]", ")", "{", "if", "(", "preg_match", "(", "$", "pattern", ",", "$", "subject", ",", "$", "match", ")", ")", "{", "$", "version", "...
Identify the version based on a pattern @param string $pattern The regular expression that defines the group that matches the version string @param string $subject The string the regular expression is matched with @param array|null $defaults An optional array of properties to set together with the value @return string
[ "Identify", "the", "version", "based", "on", "a", "pattern" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Primitive/NameVersion.php#L53-L72
train
WhichBrowser/Parser-PHP
src/Model/Browser.php
Browser.isUsing
public function isUsing($name) { if (isset($this->using)) { if ($this->using->getName() == $name) { return true; } } return false; }
php
public function isUsing($name) { if (isset($this->using)) { if ($this->using->getName() == $name) { return true; } } return false; }
[ "public", "function", "isUsing", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "using", ")", ")", "{", "if", "(", "$", "this", "->", "using", "->", "getName", "(", ")", "==", "$", "name", ")", "{", "return", "true", ";...
Is the browser using the specified webview @param string $name The name of the webview @return boolean
[ "Is", "the", "browser", "using", "the", "specified", "webview" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Browser.php#L105-L114
train
WhichBrowser/Parser-PHP
src/Model/Browser.php
Browser.toString
public function toString() { if ($this->hidden) { return ''; } $result = trim($this->getName() . ' ' . (!empty($this->version) && !$this->version->hidden ? $this->getVersion() : '')); if (empty($result) && isset($this->using)) { return $this->using->toString(); } return $result; }
php
public function toString() { if ($this->hidden) { return ''; } $result = trim($this->getName() . ' ' . (!empty($this->version) && !$this->version->hidden ? $this->getVersion() : '')); if (empty($result) && isset($this->using)) { return $this->using->toString(); } return $result; }
[ "public", "function", "toString", "(", ")", "{", "if", "(", "$", "this", "->", "hidden", ")", "{", "return", "''", ";", "}", "$", "result", "=", "trim", "(", "$", "this", "->", "getName", "(", ")", ".", "' '", ".", "(", "!", "empty", "(", "$", ...
Get a combined name and version number in a human readable format @return string
[ "Get", "a", "combined", "name", "and", "version", "number", "in", "a", "human", "readable", "format" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Browser.php#L123-L136
train
WhichBrowser/Parser-PHP
src/Model/Version.php
Version.is
public function is() { $valid = false; $arguments = func_get_args(); if (count($arguments)) { $operator = '='; $compare = null; if (count($arguments) == 1) { $compare = $arguments[0]; } if (count($arguments) >= 2) { $operator = $arguments[0]; $compare = $arguments[1]; } if (!is_null($compare)) { $min = min(substr_count($this->value, '.'), substr_count($compare, '.')) + 1; $v1 = $this->toValue($this->value, $min); $v2 = $this->toValue($compare, $min); switch ($operator) { case '<': $valid = $v1 < $v2; break; case '<=': $valid = $v1 <= $v2; break; case '=': $valid = $v1 == $v2; break; case '>': $valid = $v1 > $v2; break; case '>=': $valid = $v1 >= $v2; break; } } } return $valid; }
php
public function is() { $valid = false; $arguments = func_get_args(); if (count($arguments)) { $operator = '='; $compare = null; if (count($arguments) == 1) { $compare = $arguments[0]; } if (count($arguments) >= 2) { $operator = $arguments[0]; $compare = $arguments[1]; } if (!is_null($compare)) { $min = min(substr_count($this->value, '.'), substr_count($compare, '.')) + 1; $v1 = $this->toValue($this->value, $min); $v2 = $this->toValue($compare, $min); switch ($operator) { case '<': $valid = $v1 < $v2; break; case '<=': $valid = $v1 <= $v2; break; case '=': $valid = $v1 == $v2; break; case '>': $valid = $v1 > $v2; break; case '>=': $valid = $v1 >= $v2; break; } } } return $valid; }
[ "public", "function", "is", "(", ")", "{", "$", "valid", "=", "false", ";", "$", "arguments", "=", "func_get_args", "(", ")", ";", "if", "(", "count", "(", "$", "arguments", ")", ")", "{", "$", "operator", "=", "'='", ";", "$", "compare", "=", "n...
Determine if the version is lower, equal or higher than the specified value @param string The operator, must be <, <=, =, >= or > @param mixed The value, can be an integer, float or string with a version number @return boolean
[ "Determine", "if", "the", "version", "is", "lower", "equal", "or", "higher", "than", "the", "specified", "value" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Version.php#L38-L83
train
WhichBrowser/Parser-PHP
src/Model/Version.php
Version.getParts
public function getParts() { $parts = explode('.', $this->value); return (object) [ 'major' => !empty($parts[0]) ? intval($parts[0]) : 0, 'minor' => !empty($parts[1]) ? intval($parts[1]) : 0, 'patch' => !empty($parts[2]) ? intval($parts[2]) : 0, ]; }
php
public function getParts() { $parts = explode('.', $this->value); return (object) [ 'major' => !empty($parts[0]) ? intval($parts[0]) : 0, 'minor' => !empty($parts[1]) ? intval($parts[1]) : 0, 'patch' => !empty($parts[2]) ? intval($parts[2]) : 0, ]; }
[ "public", "function", "getParts", "(", ")", "{", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "this", "->", "value", ")", ";", "return", "(", "object", ")", "[", "'major'", "=>", "!", "empty", "(", "$", "parts", "[", "0", "]", ")", "?", ...
Return an object with each part of the version number @return object
[ "Return", "an", "object", "with", "each", "part", "of", "the", "version", "number" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Version.php#L92-L101
train
WhichBrowser/Parser-PHP
src/Model/Version.php
Version.toValue
private function toValue($value = null, $count = null) { if (is_null($value)) { $value = $this->value; } $parts = explode('.', $value); if (!is_null($count)) { $parts = array_slice($parts, 0, $count); } $result = $parts[0]; if (count($parts) > 1) { $result .= '.'; $count = count($parts); for ($p = 1; $p < $count; $p++) { $result .= substr('0000' . $parts[$p], -4); } } return floatval($result); }
php
private function toValue($value = null, $count = null) { if (is_null($value)) { $value = $this->value; } $parts = explode('.', $value); if (!is_null($count)) { $parts = array_slice($parts, 0, $count); } $result = $parts[0]; if (count($parts) > 1) { $result .= '.'; $count = count($parts); for ($p = 1; $p < $count; $p++) { $result .= substr('0000' . $parts[$p], -4); } } return floatval($result); }
[ "private", "function", "toValue", "(", "$", "value", "=", "null", ",", "$", "count", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "value", ")", ")", "{", "$", "value", "=", "$", "this", "->", "value", ";", "}", "$", "parts", "=", "exp...
Convert a version string seperated by dots into a float that can be compared @internal @param string Version string, with elements seperated by a dot @param int The maximum precision @return float
[ "Convert", "a", "version", "string", "seperated", "by", "dots", "into", "a", "float", "that", "can", "be", "compared" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Version.php#L151-L174
train
WhichBrowser/Parser-PHP
src/Model/Version.php
Version.toString
public function toString() { if (!empty($this->alias)) { return $this->alias; } $version = ''; if (!empty($this->nickname)) { $version .= $this->nickname . ' '; } if (!empty($this->value)) { if (preg_match("/([0-9]+)(?:\.([0-9]+))?(?:\.([0-9]+))?(?:\.([0-9]+))?(?:([ab])([0-9]+))?/", $this->value, $match)) { $v = [ $match[1] ]; if (array_key_exists(2, $match) && strlen($match[2])) { $v[] = $match[2]; } if (array_key_exists(3, $match) && strlen($match[3])) { $v[] = $match[3]; } if (array_key_exists(4, $match) && strlen($match[4])) { $v[] = $match[4]; } if (!empty($this->details)) { if ($this->details < 0) { array_splice($v, $this->details, 0 - $this->details); } if ($this->details > 0) { array_splice($v, $this->details, count($v) - $this->details); } } if (isset($this->builds) && !$this->builds) { $count = count($v); for ($i = 0; $i < $count; $i++) { if ($v[$i] > 999) { array_splice($v, $i, 1); } } } $version .= implode($v, '.'); if (array_key_exists(5, $match) && strlen($match[5])) { $version .= $match[5] . (!empty($match[6]) ? $match[6] : ''); } } } return $version; }
php
public function toString() { if (!empty($this->alias)) { return $this->alias; } $version = ''; if (!empty($this->nickname)) { $version .= $this->nickname . ' '; } if (!empty($this->value)) { if (preg_match("/([0-9]+)(?:\.([0-9]+))?(?:\.([0-9]+))?(?:\.([0-9]+))?(?:([ab])([0-9]+))?/", $this->value, $match)) { $v = [ $match[1] ]; if (array_key_exists(2, $match) && strlen($match[2])) { $v[] = $match[2]; } if (array_key_exists(3, $match) && strlen($match[3])) { $v[] = $match[3]; } if (array_key_exists(4, $match) && strlen($match[4])) { $v[] = $match[4]; } if (!empty($this->details)) { if ($this->details < 0) { array_splice($v, $this->details, 0 - $this->details); } if ($this->details > 0) { array_splice($v, $this->details, count($v) - $this->details); } } if (isset($this->builds) && !$this->builds) { $count = count($v); for ($i = 0; $i < $count; $i++) { if ($v[$i] > 999) { array_splice($v, $i, 1); } } } $version .= implode($v, '.'); if (array_key_exists(5, $match) && strlen($match[5])) { $version .= $match[5] . (!empty($match[6]) ? $match[6] : ''); } } } return $version; }
[ "public", "function", "toString", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "alias", ")", ")", "{", "return", "$", "this", "->", "alias", ";", "}", "$", "version", "=", "''", ";", "if", "(", "!", "empty", "(", "$", "this",...
Return the version as a human readable string @return string
[ "Return", "the", "version", "as", "a", "human", "readable", "string" ]
9c6ad8eadc23294b1c66d92876c11f13c5d4cf48
https://github.com/WhichBrowser/Parser-PHP/blob/9c6ad8eadc23294b1c66d92876c11f13c5d4cf48/src/Model/Version.php#L207-L263
train
jaggedsoft/php-binance-api
php-binance-api.php
API.buy
public function buy(string $symbol, $quantity, $price, string $type = "LIMIT", array $flags = []) { return $this->order("BUY", $symbol, $quantity, $price, $type, $flags); }
php
public function buy(string $symbol, $quantity, $price, string $type = "LIMIT", array $flags = []) { return $this->order("BUY", $symbol, $quantity, $price, $type, $flags); }
[ "public", "function", "buy", "(", "string", "$", "symbol", ",", "$", "quantity", ",", "$", "price", ",", "string", "$", "type", "=", "\"LIMIT\"", ",", "array", "$", "flags", "=", "[", "]", ")", "{", "return", "$", "this", "->", "order", "(", "\"BUY...
buy attempts to create a currency order each currency supports a number of order types, such as -LIMIT -MARKET -STOP_LOSS -STOP_LOSS_LIMIT -TAKE_PROFIT -TAKE_PROFIT_LIMIT -LIMIT_MAKER You should check the @see exchangeInfo for each currency to determine what types of orders can be placed against specific pairs $quantity = 1; $price = 0.0005; $order = $api->buy("BNBBTC", $quantity, $price); @param $symbol string the currency symbol @param $quantity string the quantity required @param $price string price per unit you want to spend @param $type string type of order @param $flags array addtional options for order type @return array with error message or the order details
[ "buy", "attempts", "to", "create", "a", "currency", "order", "each", "currency", "supports", "a", "number", "of", "order", "types", "such", "as", "-", "LIMIT", "-", "MARKET", "-", "STOP_LOSS", "-", "STOP_LOSS_LIMIT", "-", "TAKE_PROFIT", "-", "TAKE_PROFIT_LIMIT...
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L227-L230
train
jaggedsoft/php-binance-api
php-binance-api.php
API.marketBuy
public function marketBuy(string $symbol, $quantity, array $flags = []) { return $this->order("BUY", $symbol, $quantity, 0, "MARKET", $flags); }
php
public function marketBuy(string $symbol, $quantity, array $flags = []) { return $this->order("BUY", $symbol, $quantity, 0, "MARKET", $flags); }
[ "public", "function", "marketBuy", "(", "string", "$", "symbol", ",", "$", "quantity", ",", "array", "$", "flags", "=", "[", "]", ")", "{", "return", "$", "this", "->", "order", "(", "\"BUY\"", ",", "$", "symbol", ",", "$", "quantity", ",", "0", ",...
marketBuy attempts to create a currency order at given market price $quantity = 1; $order = $api->marketBuy("BNBBTC", $quantity); @param $symbol string the currency symbol @param $quantity string the quantity required @param $flags array addtional options for order type @return array with error message or the order details
[ "marketBuy", "attempts", "to", "create", "a", "currency", "order", "at", "given", "market", "price" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L307-L310
train
jaggedsoft/php-binance-api
php-binance-api.php
API.marketSell
public function marketSell(string $symbol, $quantity, array $flags = []) { return $this->order("SELL", $symbol, $quantity, 0, "MARKET", $flags); }
php
public function marketSell(string $symbol, $quantity, array $flags = []) { return $this->order("SELL", $symbol, $quantity, 0, "MARKET", $flags); }
[ "public", "function", "marketSell", "(", "string", "$", "symbol", ",", "$", "quantity", ",", "array", "$", "flags", "=", "[", "]", ")", "{", "return", "$", "this", "->", "order", "(", "\"SELL\"", ",", "$", "symbol", ",", "$", "quantity", ",", "0", ...
marketSell attempts to create a currency order at given market price $quantity = 1; $order = $api->marketSell("BNBBTC", $quantity); @param $symbol string the currency symbol @param $quantity string the quantity required @param $flags array addtional options for order type @return array with error message or the order details
[ "marketSell", "attempts", "to", "create", "a", "currency", "order", "at", "given", "market", "price" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L338-L341
train
jaggedsoft/php-binance-api
php-binance-api.php
API.cancel
public function cancel(string $symbol, $orderid, $flags = []) { $params = [ "symbol" => $symbol, "orderId" => $orderid, ]; return $this->httpRequest("v3/order", "DELETE", array_merge($params, $flags), true); }
php
public function cancel(string $symbol, $orderid, $flags = []) { $params = [ "symbol" => $symbol, "orderId" => $orderid, ]; return $this->httpRequest("v3/order", "DELETE", array_merge($params, $flags), true); }
[ "public", "function", "cancel", "(", "string", "$", "symbol", ",", "$", "orderid", ",", "$", "flags", "=", "[", "]", ")", "{", "$", "params", "=", "[", "\"symbol\"", "=>", "$", "symbol", ",", "\"orderId\"", "=>", "$", "orderid", ",", "]", ";", "ret...
cancel attempts to cancel a currency order $orderid = "123456789"; $order = $api->cancel("BNBBTC", $orderid); @param $symbol string the currency symbol @param $orderid string the orderid to cancel @param $flags array of optional options like ["side"=>"sell"] @return array with error message or the order details @throws \Exception
[ "cancel", "attempts", "to", "cancel", "a", "currency", "order" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L370-L377
train
jaggedsoft/php-binance-api
php-binance-api.php
API.openOrders
public function openOrders(string $symbol = null) { $params = []; if (is_null($symbol) != true) { $params = [ "symbol" => $symbol, ]; } return $this->httpRequest("v3/openOrders", "GET", $params, true); }
php
public function openOrders(string $symbol = null) { $params = []; if (is_null($symbol) != true) { $params = [ "symbol" => $symbol, ]; } return $this->httpRequest("v3/openOrders", "GET", $params, true); }
[ "public", "function", "openOrders", "(", "string", "$", "symbol", "=", "null", ")", "{", "$", "params", "=", "[", "]", ";", "if", "(", "is_null", "(", "$", "symbol", ")", "!=", "true", ")", "{", "$", "params", "=", "[", "\"symbol\"", "=>", "$", "...
openOrders attempts to get open orders for all currencies or a specific currency $allOpenOrders = $api->openOrders(); $allBNBOrders = $api->openOrders( "BNBBTC" ); @param $symbol string the currency symbol @return array with error message or the order details @throws \Exception
[ "openOrders", "attempts", "to", "get", "open", "orders", "for", "all", "currencies", "or", "a", "specific", "currency" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L408-L417
train
jaggedsoft/php-binance-api
php-binance-api.php
API.orders
public function orders(string $symbol, int $limit = 500, int $fromOrderId = 1) { return $this->httpRequest("v3/allOrders", "GET", [ "symbol" => $symbol, "limit" => $limit, "orderId" => $fromOrderId, ], true); }
php
public function orders(string $symbol, int $limit = 500, int $fromOrderId = 1) { return $this->httpRequest("v3/allOrders", "GET", [ "symbol" => $symbol, "limit" => $limit, "orderId" => $fromOrderId, ], true); }
[ "public", "function", "orders", "(", "string", "$", "symbol", ",", "int", "$", "limit", "=", "500", ",", "int", "$", "fromOrderId", "=", "1", ")", "{", "return", "$", "this", "->", "httpRequest", "(", "\"v3/allOrders\"", ",", "\"GET\"", ",", "[", "\"sy...
orders attempts to get the orders for all or a specific currency $allBNBOrders = $api->orders( "BNBBTC" ); @param $symbol string the currency symbol @param $limit int the amount of orders returned @param $fromOrderId string return the orders from this order onwards @return array with error message or array of orderDetails array @throws \Exception
[ "orders", "attempts", "to", "get", "the", "orders", "for", "all", "or", "a", "specific", "currency" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L430-L437
train
jaggedsoft/php-binance-api
php-binance-api.php
API.history
public function history(string $symbol, int $limit = 500, int $fromTradeId = -1) { $parameters = [ "symbol" => $symbol, "limit" => $limit, ]; if ($fromTradeId > 0) { $parameters["fromId"] = $fromTradeId; } return $this->httpRequest("v3/myTrades", "GET", $parameters, true); }
php
public function history(string $symbol, int $limit = 500, int $fromTradeId = -1) { $parameters = [ "symbol" => $symbol, "limit" => $limit, ]; if ($fromTradeId > 0) { $parameters["fromId"] = $fromTradeId; } return $this->httpRequest("v3/myTrades", "GET", $parameters, true); }
[ "public", "function", "history", "(", "string", "$", "symbol", ",", "int", "$", "limit", "=", "500", ",", "int", "$", "fromTradeId", "=", "-", "1", ")", "{", "$", "parameters", "=", "[", "\"symbol\"", "=>", "$", "symbol", ",", "\"limit\"", "=>", "$",...
history Get the complete account trade history for all or a specific currency $allHistory = $api->history(); $BNBHistory = $api->history("BNBBTC"); $limitBNBHistory = $api->history("BNBBTC",5); $limitBNBHistoryFromId = $api->history("BNBBTC",5,3); @param $symbol string the currency symbol @param $limit int the amount of orders returned @param $fromTradeId int (optional) return the orders from this order onwards. negative for all @return array with error message or array of orderDetails array @throws \Exception
[ "history", "Get", "the", "complete", "account", "trade", "history", "for", "all", "or", "a", "specific", "currency" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L453-L464
train
jaggedsoft/php-binance-api
php-binance-api.php
API.useServerTime
public function useServerTime() { $request = $this->httpRequest("v1/time"); if (isset($request['serverTime'])) { $this->info['timeOffset'] = $request['serverTime'] - (microtime(true) * 1000); } }
php
public function useServerTime() { $request = $this->httpRequest("v1/time"); if (isset($request['serverTime'])) { $this->info['timeOffset'] = $request['serverTime'] - (microtime(true) * 1000); } }
[ "public", "function", "useServerTime", "(", ")", "{", "$", "request", "=", "$", "this", "->", "httpRequest", "(", "\"v1/time\"", ")", ";", "if", "(", "isset", "(", "$", "request", "[", "'serverTime'", "]", ")", ")", "{", "$", "this", "->", "info", "[...
useServerTime adds the 'useServerTime'=>true to the API request to avoid time errors $api->useServerTime(); @return null @throws \Exception
[ "useServerTime", "adds", "the", "useServerTime", "=", ">", "true", "to", "the", "API", "request", "to", "avoid", "time", "errors" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L474-L480
train
jaggedsoft/php-binance-api
php-binance-api.php
API.withdraw
public function withdraw(string $asset, string $address, $amount, $addressTag = null) { $options = [ "asset" => $asset, "address" => $address, "amount" => $amount, "wapi" => true, "name" => "API Withdraw", ]; if (is_null($addressTag) === false && is_empty($addressTag) === false) { $options['addressTag'] = $addressTag; } return $this->httpRequest("v3/withdraw.html", "POST", $options, true); }
php
public function withdraw(string $asset, string $address, $amount, $addressTag = null) { $options = [ "asset" => $asset, "address" => $address, "amount" => $amount, "wapi" => true, "name" => "API Withdraw", ]; if (is_null($addressTag) === false && is_empty($addressTag) === false) { $options['addressTag'] = $addressTag; } return $this->httpRequest("v3/withdraw.html", "POST", $options, true); }
[ "public", "function", "withdraw", "(", "string", "$", "asset", ",", "string", "$", "address", ",", "$", "amount", ",", "$", "addressTag", "=", "null", ")", "{", "$", "options", "=", "[", "\"asset\"", "=>", "$", "asset", ",", "\"address\"", "=>", "$", ...
withdraw requests a asset be withdrawn from binance to another wallet $asset = "BTC"; $address = "1C5gqLRs96Xq4V2ZZAR1347yUCpHie7sa"; $amount = 0.2; $response = $api->withdraw($asset, $address, $amount); $address = "44tLjmXrQNrWJ5NBsEj2R77ZBEgDa3fEe9GLpSf2FRmhexPvfYDUAB7EXX1Hdb3aMQ9FLqdJ56yaAhiXoRsceGJCRS3Jxkn"; $addressTag = "0e5e38a01058dbf64e53a4333a5acf98e0d5feb8e523d32e3186c664a9c762c1"; $amount = 0.1; $response = $api->withdraw($asset, $address, $amount, $addressTag); @param $asset string the currency such as BTC @param $address string the addressed to whihc the asset should be deposited @param $amount double the amount of the asset to transfer @param $addressTag string adtional transactionid required by some assets @return array with error message or array transaction @throws \Exception
[ "withdraw", "requests", "a", "asset", "be", "withdrawn", "from", "binance", "to", "another", "wallet" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L534-L547
train
jaggedsoft/php-binance-api
php-binance-api.php
API.depositAddress
public function depositAddress(string $asset) { $params = [ "wapi" => true, "asset" => $asset, ]; return $this->httpRequest("v3/depositAddress.html", "GET", $params, true); }
php
public function depositAddress(string $asset) { $params = [ "wapi" => true, "asset" => $asset, ]; return $this->httpRequest("v3/depositAddress.html", "GET", $params, true); }
[ "public", "function", "depositAddress", "(", "string", "$", "asset", ")", "{", "$", "params", "=", "[", "\"wapi\"", "=>", "true", ",", "\"asset\"", "=>", "$", "asset", ",", "]", ";", "return", "$", "this", "->", "httpRequest", "(", "\"v3/depositAddress.htm...
depositAddress get the deposit address for an asset $depositAddress = $api->depositAddress("VEN"); @param $asset string the currency such as BTC @return array with error message or array deposit address information @throws \Exception
[ "depositAddress", "get", "the", "deposit", "address", "for", "an", "asset" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L558-L565
train
jaggedsoft/php-binance-api
php-binance-api.php
API.depositHistory
public function depositHistory(string $asset = null, array $params = []) { $params["wapi"] = true; if (is_null($asset) === false) { $params['asset'] = $asset; } return $this->httpRequest("v3/depositHistory.html", "GET", $params, true); }
php
public function depositHistory(string $asset = null, array $params = []) { $params["wapi"] = true; if (is_null($asset) === false) { $params['asset'] = $asset; } return $this->httpRequest("v3/depositHistory.html", "GET", $params, true); }
[ "public", "function", "depositHistory", "(", "string", "$", "asset", "=", "null", ",", "array", "$", "params", "=", "[", "]", ")", "{", "$", "params", "[", "\"wapi\"", "]", "=", "true", ";", "if", "(", "is_null", "(", "$", "asset", ")", "===", "fal...
depositAddress get the deposit history for an asset $depositHistory = $api->depositHistory(); $depositHistory = $api->depositHistory( "BTC" ); @param $asset string empty or the currency such as BTC @param $params array optional startTime, endTime, status parameters @return array with error message or array deposit history information @throws \Exception
[ "depositAddress", "get", "the", "deposit", "history", "for", "an", "asset" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L579-L586
train
jaggedsoft/php-binance-api
php-binance-api.php
API.withdrawFee
public function withdrawFee(string $asset) { $params = [ "wapi" => true, ]; $response = $this->httpRequest("v3/assetDetail.html", "GET", $params, true); if (isset($response['success'], $response['assetDetail'], $response['assetDetail'][$asset]) && $response['success']) { return $response['assetDetail'][$asset]; } }
php
public function withdrawFee(string $asset) { $params = [ "wapi" => true, ]; $response = $this->httpRequest("v3/assetDetail.html", "GET", $params, true); if (isset($response['success'], $response['assetDetail'], $response['assetDetail'][$asset]) && $response['success']) { return $response['assetDetail'][$asset]; } }
[ "public", "function", "withdrawFee", "(", "string", "$", "asset", ")", "{", "$", "params", "=", "[", "\"wapi\"", "=>", "true", ",", "]", ";", "$", "response", "=", "$", "this", "->", "httpRequest", "(", "\"v3/assetDetail.html\"", ",", "\"GET\"", ",", "$"...
withdrawFee get the withdrawal fee for an asset $withdrawFee = $api->withdrawFee( "BTC" ); @param $asset string currency such as BTC @return array with error message or array containing withdrawFee @throws \Exception
[ "withdrawFee", "get", "the", "withdrawal", "fee", "for", "an", "asset" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L618-L629
train
jaggedsoft/php-binance-api
php-binance-api.php
API.prevDay
public function prevDay(string $symbol = null) { $additionalData = []; if (is_null($symbol) === false) { $additionalData = [ 'symbol' => $symbol, ]; } return $this->httpRequest("v1/ticker/24hr", "GET", $additionalData); }
php
public function prevDay(string $symbol = null) { $additionalData = []; if (is_null($symbol) === false) { $additionalData = [ 'symbol' => $symbol, ]; } return $this->httpRequest("v1/ticker/24hr", "GET", $additionalData); }
[ "public", "function", "prevDay", "(", "string", "$", "symbol", "=", "null", ")", "{", "$", "additionalData", "=", "[", "]", ";", "if", "(", "is_null", "(", "$", "symbol", ")", "===", "false", ")", "{", "$", "additionalData", "=", "[", "'symbol'", "=>...
prevDay get 24hr ticker price change statistics for symbols $prevDay = $api->prevDay("BNBBTC"); @param $symbol (optional) symbol to get the previous day change for @return array with error message or array of prevDay change @throws \Exception
[ "prevDay", "get", "24hr", "ticker", "price", "change", "statistics", "for", "symbols" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L694-L703
train
jaggedsoft/php-binance-api
php-binance-api.php
API.depth
public function depth(string $symbol, int $limit = 100) { if (is_int($limit) === false) { $limit = 100; } if (isset($symbol) === false || is_string($symbol) === false) { // WPCS: XSS OK. echo "asset: expected bool false, " . gettype($symbol) . " given" . PHP_EOL; } $json = $this->httpRequest("v1/depth", "GET", [ "symbol" => $symbol, "limit" => $limit, ]); if (isset($this->info[$symbol]) === false) { $this->info[$symbol] = []; } $this->info[$symbol]['firstUpdate'] = $json['lastUpdateId']; return $this->depthData($symbol, $json); }
php
public function depth(string $symbol, int $limit = 100) { if (is_int($limit) === false) { $limit = 100; } if (isset($symbol) === false || is_string($symbol) === false) { // WPCS: XSS OK. echo "asset: expected bool false, " . gettype($symbol) . " given" . PHP_EOL; } $json = $this->httpRequest("v1/depth", "GET", [ "symbol" => $symbol, "limit" => $limit, ]); if (isset($this->info[$symbol]) === false) { $this->info[$symbol] = []; } $this->info[$symbol]['firstUpdate'] = $json['lastUpdateId']; return $this->depthData($symbol, $json); }
[ "public", "function", "depth", "(", "string", "$", "symbol", ",", "int", "$", "limit", "=", "100", ")", "{", "if", "(", "is_int", "(", "$", "limit", ")", "===", "false", ")", "{", "$", "limit", "=", "100", ";", "}", "if", "(", "isset", "(", "$"...
depth get Market depth $depth = $api->depth("ETHBTC"); @param $symbol string the symbol to get the depth information for @param $limit int set limition for number of market depth data @return array with error message or array of market depth @throws \Exception
[ "depth", "get", "Market", "depth" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L731-L750
train
jaggedsoft/php-binance-api
php-binance-api.php
API.balances
public function balances($priceData = false) { if (is_array($priceData) === false) { $priceData = false; } $account = $this->httpRequest("v3/account", "GET", [], true); if (is_array($account) === false) { echo "Error: unable to fetch your account details" . PHP_EOL; } if (isset($account['balances']) === false) { echo "Error: your balances were empty or unset" . PHP_EOL; } return $this->balanceData($account, $priceData); }
php
public function balances($priceData = false) { if (is_array($priceData) === false) { $priceData = false; } $account = $this->httpRequest("v3/account", "GET", [], true); if (is_array($account) === false) { echo "Error: unable to fetch your account details" . PHP_EOL; } if (isset($account['balances']) === false) { echo "Error: your balances were empty or unset" . PHP_EOL; } return $this->balanceData($account, $priceData); }
[ "public", "function", "balances", "(", "$", "priceData", "=", "false", ")", "{", "if", "(", "is_array", "(", "$", "priceData", ")", "===", "false", ")", "{", "$", "priceData", "=", "false", ";", "}", "$", "account", "=", "$", "this", "->", "httpReque...
balances get balances for the account assets $balances = $api->balances($ticker); @param bool $priceData array of the symbols balances are required for @return array with error message or array of balances @throws \Exception
[ "balances", "get", "balances", "for", "the", "account", "assets" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L761-L778
train
jaggedsoft/php-binance-api
php-binance-api.php
API.getProxyUriString
public function getProxyUriString() { $uri = isset($this->proxyConf['proto']) ? $this->proxyConf['proto'] : "http"; // https://curl.haxx.se/libcurl/c/CURLOPT_PROXY.html $supportedProtocols = array( 'http', 'https', 'socks4', 'socks4a', 'socks5', 'socks5h', ); if (in_array($uri, $supportedProtocols) === false) { // WPCS: XSS OK. echo "Unknown proxy protocol '" . $this->proxyConf['proto'] . "', supported protocols are " . implode(", ", $supportedProtocols) . PHP_EOL; } $uri .= "://"; $uri .= isset($this->proxyConf['address']) ? $this->proxyConf['address'] : "localhost"; if (isset($this->proxyConf['address']) === false) { // WPCS: XSS OK. echo "warning: proxy address not set defaulting to localhost" . PHP_EOL; } $uri .= ":"; $uri .= isset($this->proxyConf['port']) ? $this->proxyConf['port'] : "1080"; if (isset($this->proxyConf['address']) === false) { // WPCS: XSS OK. echo "warning: proxy port not set defaulting to 1080" . PHP_EOL; } return $uri; }
php
public function getProxyUriString() { $uri = isset($this->proxyConf['proto']) ? $this->proxyConf['proto'] : "http"; // https://curl.haxx.se/libcurl/c/CURLOPT_PROXY.html $supportedProtocols = array( 'http', 'https', 'socks4', 'socks4a', 'socks5', 'socks5h', ); if (in_array($uri, $supportedProtocols) === false) { // WPCS: XSS OK. echo "Unknown proxy protocol '" . $this->proxyConf['proto'] . "', supported protocols are " . implode(", ", $supportedProtocols) . PHP_EOL; } $uri .= "://"; $uri .= isset($this->proxyConf['address']) ? $this->proxyConf['address'] : "localhost"; if (isset($this->proxyConf['address']) === false) { // WPCS: XSS OK. echo "warning: proxy address not set defaulting to localhost" . PHP_EOL; } $uri .= ":"; $uri .= isset($this->proxyConf['port']) ? $this->proxyConf['port'] : "1080"; if (isset($this->proxyConf['address']) === false) { // WPCS: XSS OK. echo "warning: proxy port not set defaulting to 1080" . PHP_EOL; } return $uri; }
[ "public", "function", "getProxyUriString", "(", ")", "{", "$", "uri", "=", "isset", "(", "$", "this", "->", "proxyConf", "[", "'proto'", "]", ")", "?", "$", "this", "->", "proxyConf", "[", "'proto'", "]", ":", "\"http\"", ";", "// https://curl.haxx.se/libc...
getProxyUriString get Uniform Resource Identifier string assocaited with proxy config $balances = $api->getProxyUriString(); @return string uri
[ "getProxyUriString", "get", "Uniform", "Resource", "Identifier", "string", "assocaited", "with", "proxy", "config" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L787-L822
train
jaggedsoft/php-binance-api
php-binance-api.php
API.order
public function order(string $side, string $symbol, $quantity, $price, string $type = "LIMIT", array $flags = [], bool $test = false) { $opt = [ "symbol" => $symbol, "side" => $side, "type" => $type, "quantity" => $quantity, "recvWindow" => 60000, ]; // someone has preformated there 8 decimal point double already // dont do anything, leave them do whatever they want if (gettype($price) !== "string") { // for every other type, lets format it appropriately $price = number_format($price, 8, '.', ''); } if (is_numeric($quantity) === false) { // WPCS: XSS OK. echo "warning: quantity expected numeric got " . gettype($quantity) . PHP_EOL; } if (is_string($price) === false) { // WPCS: XSS OK. echo "warning: price expected string got " . gettype($price) . PHP_EOL; } if ($type === "LIMIT" || $type === "STOP_LOSS_LIMIT" || $type === "TAKE_PROFIT_LIMIT") { $opt["price"] = $price; $opt["timeInForce"] = "GTC"; } if (isset($flags['stopPrice'])) { $opt['stopPrice'] = $flags['stopPrice']; } if (isset($flags['icebergQty'])) { $opt['icebergQty'] = $flags['icebergQty']; } if (isset($flags['newOrderRespType'])) { $opt['newOrderRespType'] = $flags['newOrderRespType']; } $qstring = ($test === false) ? "v3/order" : "v3/order/test"; return $this->httpRequest($qstring, "POST", $opt, true); }
php
public function order(string $side, string $symbol, $quantity, $price, string $type = "LIMIT", array $flags = [], bool $test = false) { $opt = [ "symbol" => $symbol, "side" => $side, "type" => $type, "quantity" => $quantity, "recvWindow" => 60000, ]; // someone has preformated there 8 decimal point double already // dont do anything, leave them do whatever they want if (gettype($price) !== "string") { // for every other type, lets format it appropriately $price = number_format($price, 8, '.', ''); } if (is_numeric($quantity) === false) { // WPCS: XSS OK. echo "warning: quantity expected numeric got " . gettype($quantity) . PHP_EOL; } if (is_string($price) === false) { // WPCS: XSS OK. echo "warning: price expected string got " . gettype($price) . PHP_EOL; } if ($type === "LIMIT" || $type === "STOP_LOSS_LIMIT" || $type === "TAKE_PROFIT_LIMIT") { $opt["price"] = $price; $opt["timeInForce"] = "GTC"; } if (isset($flags['stopPrice'])) { $opt['stopPrice'] = $flags['stopPrice']; } if (isset($flags['icebergQty'])) { $opt['icebergQty'] = $flags['icebergQty']; } if (isset($flags['newOrderRespType'])) { $opt['newOrderRespType'] = $flags['newOrderRespType']; } $qstring = ($test === false) ? "v3/order" : "v3/order/test"; return $this->httpRequest($qstring, "POST", $opt, true); }
[ "public", "function", "order", "(", "string", "$", "side", ",", "string", "$", "symbol", ",", "$", "quantity", ",", "$", "price", ",", "string", "$", "type", "=", "\"LIMIT\"", ",", "array", "$", "flags", "=", "[", "]", ",", "bool", "$", "test", "="...
order formats the orders before sending them to the curl wrapper function You can call this function directly or use the helper functions @see buy() @see sell() @see marketBuy() @see marketSell() $this->httpRequest( "https://api.binance.com/api/v1/ticker/24hr"); @param $side string typically "BUY" or "SELL" @param $symbol string to buy or sell @param $quantity string in the order @param $price string for the order @param $type string is determined by the symbol bu typicall LIMIT, STOP_LOSS_LIMIT etc. @param $flags array additional transaction options @param $test bool whether to test or not, test only validates the query @return array containing the response @throws \Exception
[ "order", "formats", "the", "orders", "before", "sending", "them", "to", "the", "curl", "wrapper", "function", "You", "can", "call", "this", "function", "directly", "or", "use", "the", "helper", "functions" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L996-L1042
train
jaggedsoft/php-binance-api
php-binance-api.php
API.candlesticks
public function candlesticks(string $symbol, string $interval = "5m", int $limit = null, $startTime = null, $endTime = null) { if (!isset($this->charts[$symbol])) { $this->charts[$symbol] = []; } $opt = [ "symbol" => $symbol, "interval" => $interval, ]; if ($limit) { $opt["limit"] = $limit; } if ($startTime) { $opt["startTime"] = $startTime; } if ($endTime) { $opt["endTime"] = $endTime; } $response = $this->httpRequest("v1/klines", "GET", $opt); if (is_array($response) === false) { return []; } if (count($response) === 0) { echo "warning: v1/klines returned empty array, usually a blip in the connection or server" . PHP_EOL; return []; } $ticks = $this->chartData($symbol, $interval, $response); $this->charts[$symbol][$interval] = $ticks; return $ticks; }
php
public function candlesticks(string $symbol, string $interval = "5m", int $limit = null, $startTime = null, $endTime = null) { if (!isset($this->charts[$symbol])) { $this->charts[$symbol] = []; } $opt = [ "symbol" => $symbol, "interval" => $interval, ]; if ($limit) { $opt["limit"] = $limit; } if ($startTime) { $opt["startTime"] = $startTime; } if ($endTime) { $opt["endTime"] = $endTime; } $response = $this->httpRequest("v1/klines", "GET", $opt); if (is_array($response) === false) { return []; } if (count($response) === 0) { echo "warning: v1/klines returned empty array, usually a blip in the connection or server" . PHP_EOL; return []; } $ticks = $this->chartData($symbol, $interval, $response); $this->charts[$symbol][$interval] = $ticks; return $ticks; }
[ "public", "function", "candlesticks", "(", "string", "$", "symbol", ",", "string", "$", "interval", "=", "\"5m\"", ",", "int", "$", "limit", "=", "null", ",", "$", "startTime", "=", "null", ",", "$", "endTime", "=", "null", ")", "{", "if", "(", "!", ...
candlesticks get the candles for the given intervals 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M $candles = $api->candlesticks("BNBBTC", "5m"); @param $symbol string to query @param $interval string to request @param $limit int limit the amount of candles @param $startTime string request candle information starting from here @param $endTime string request candle information ending here @return array containing the response @throws \Exception
[ "candlesticks", "get", "the", "candles", "for", "the", "given", "intervals", "1m", "3m", "5m", "15m", "30m", "1h", "2h", "4h", "6h", "8h", "12h", "1d", "3d", "1w", "1M" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1058-L1095
train
jaggedsoft/php-binance-api
php-binance-api.php
API.balanceHandler
private function balanceHandler(array $json) { $balances = []; foreach ($json as $item) { $asset = $item->a; $available = $item->f; $onOrder = $item->l; $balances[$asset] = [ "available" => $available, "onOrder" => $onOrder, ]; } return $balances; }
php
private function balanceHandler(array $json) { $balances = []; foreach ($json as $item) { $asset = $item->a; $available = $item->f; $onOrder = $item->l; $balances[$asset] = [ "available" => $available, "onOrder" => $onOrder, ]; } return $balances; }
[ "private", "function", "balanceHandler", "(", "array", "$", "json", ")", "{", "$", "balances", "=", "[", "]", ";", "foreach", "(", "$", "json", "as", "$", "item", ")", "{", "$", "asset", "=", "$", "item", "->", "a", ";", "$", "available", "=", "$...
balanceHandler Convert balance WebSocket data into array $data = $this->balanceHandler( $json ); @param $json array data to convert @return array
[ "balanceHandler", "Convert", "balance", "WebSocket", "data", "into", "array" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1183-L1196
train
jaggedsoft/php-binance-api
php-binance-api.php
API.tickerStreamHandler
private function tickerStreamHandler(\stdClass $json) { return [ "eventType" => $json->e, "eventTime" => $json->E, "symbol" => $json->s, "priceChange" => $json->p, "percentChange" => $json->P, "averagePrice" => $json->w, "prevClose" => $json->x, "close" => $json->c, "closeQty" => $json->Q, "bestBid" => $json->b, "bestBidQty" => $json->B, "bestAsk" => $json->a, "bestAskQty" => $json->A, "open" => $json->o, "high" => $json->h, "low" => $json->l, "volume" => $json->v, "quoteVolume" => $json->q, "openTime" => $json->O, "closeTime" => $json->C, "firstTradeId" => $json->F, "lastTradeId" => $json->L, "numTrades" => $json->n, ]; }
php
private function tickerStreamHandler(\stdClass $json) { return [ "eventType" => $json->e, "eventTime" => $json->E, "symbol" => $json->s, "priceChange" => $json->p, "percentChange" => $json->P, "averagePrice" => $json->w, "prevClose" => $json->x, "close" => $json->c, "closeQty" => $json->Q, "bestBid" => $json->b, "bestBidQty" => $json->B, "bestAsk" => $json->a, "bestAskQty" => $json->A, "open" => $json->o, "high" => $json->h, "low" => $json->l, "volume" => $json->v, "quoteVolume" => $json->q, "openTime" => $json->O, "closeTime" => $json->C, "firstTradeId" => $json->F, "lastTradeId" => $json->L, "numTrades" => $json->n, ]; }
[ "private", "function", "tickerStreamHandler", "(", "\\", "stdClass", "$", "json", ")", "{", "return", "[", "\"eventType\"", "=>", "$", "json", "->", "e", ",", "\"eventTime\"", "=>", "$", "json", "->", "E", ",", "\"symbol\"", "=>", "$", "json", "->", "s",...
tickerStreamHandler Convert WebSocket ticker data into array $data = $this->tickerStreamHandler( $json ); @param $json object data to convert @return array
[ "tickerStreamHandler", "Convert", "WebSocket", "ticker", "data", "into", "array" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1206-L1233
train
jaggedsoft/php-binance-api
php-binance-api.php
API.executionHandler
private function executionHandler(\stdClass $json) { return [ "symbol" => $json->s, "side" => $json->S, "orderType" => $json->o, "quantity" => $json->q, "price" => $json->p, "executionType" => $json->x, "orderStatus" => $json->X, "rejectReason" => $json->r, "orderId" => $json->i, "clientOrderId" => $json->c, "orderTime" => $json->T, "eventTime" => $json->E, ]; }
php
private function executionHandler(\stdClass $json) { return [ "symbol" => $json->s, "side" => $json->S, "orderType" => $json->o, "quantity" => $json->q, "price" => $json->p, "executionType" => $json->x, "orderStatus" => $json->X, "rejectReason" => $json->r, "orderId" => $json->i, "clientOrderId" => $json->c, "orderTime" => $json->T, "eventTime" => $json->E, ]; }
[ "private", "function", "executionHandler", "(", "\\", "stdClass", "$", "json", ")", "{", "return", "[", "\"symbol\"", "=>", "$", "json", "->", "s", ",", "\"side\"", "=>", "$", "json", "->", "S", ",", "\"orderType\"", "=>", "$", "json", "->", "o", ",", ...
tickerStreamHandler Convert WebSocket trade execution into array $data = $this->executionHandler( $json ); @param \stdClass $json object data to convert @return array
[ "tickerStreamHandler", "Convert", "WebSocket", "trade", "execution", "into", "array" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1243-L1259
train
jaggedsoft/php-binance-api
php-binance-api.php
API.chartData
private function chartData(string $symbol, string $interval, array $ticks) { if (!isset($this->info[$symbol])) { $this->info[$symbol] = []; } if (!isset($this->info[$symbol][$interval])) { $this->info[$symbol][$interval] = []; } $output = []; foreach ($ticks as $tick) { list($openTime, $open, $high, $low, $close, $assetVolume, $closeTime, $baseVolume, $trades, $assetBuyVolume, $takerBuyVolume, $ignored) = $tick; $output[$openTime] = [ "open" => $open, "high" => $high, "low" => $low, "close" => $close, "volume" => $baseVolume, "openTime" => $openTime, "closeTime" => $closeTime, "assetVolume" => $assetVolume, "baseVolume" => $baseVolume, "trades" => $trades, "assetBuyVolume" => $assetBuyVolume, "takerBuyVolume" => $takerBuyVolume, "ignored" => $ignored, ]; } if (isset($openTime)) { $this->info[$symbol][$interval]['firstOpen'] = $openTime; } return $output; }
php
private function chartData(string $symbol, string $interval, array $ticks) { if (!isset($this->info[$symbol])) { $this->info[$symbol] = []; } if (!isset($this->info[$symbol][$interval])) { $this->info[$symbol][$interval] = []; } $output = []; foreach ($ticks as $tick) { list($openTime, $open, $high, $low, $close, $assetVolume, $closeTime, $baseVolume, $trades, $assetBuyVolume, $takerBuyVolume, $ignored) = $tick; $output[$openTime] = [ "open" => $open, "high" => $high, "low" => $low, "close" => $close, "volume" => $baseVolume, "openTime" => $openTime, "closeTime" => $closeTime, "assetVolume" => $assetVolume, "baseVolume" => $baseVolume, "trades" => $trades, "assetBuyVolume" => $assetBuyVolume, "takerBuyVolume" => $takerBuyVolume, "ignored" => $ignored, ]; } if (isset($openTime)) { $this->info[$symbol][$interval]['firstOpen'] = $openTime; } return $output; }
[ "private", "function", "chartData", "(", "string", "$", "symbol", ",", "string", "$", "interval", ",", "array", "$", "ticks", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "info", "[", "$", "symbol", "]", ")", ")", "{", "$", "this", ...
chartData Convert kline data into object $object = $this->chartData($symbol, $interval, $ticks); @param $symbol string of your currency @param $interval string the time interval @param $ticks array of the canbles array @return array object of the chartdata
[ "chartData", "Convert", "kline", "data", "into", "object" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1271-L1306
train
jaggedsoft/php-binance-api
php-binance-api.php
API.tradesData
private function tradesData(array $trades) { $output = []; foreach ($trades as $trade) { $price = $trade['p']; $quantity = $trade['q']; $timestamp = $trade['T']; $maker = $trade['m'] ? 'true' : 'false'; $output[] = [ "price" => $price, "quantity" => $quantity, "timestamp" => $timestamp, "maker" => $maker, ]; } return $output; }
php
private function tradesData(array $trades) { $output = []; foreach ($trades as $trade) { $price = $trade['p']; $quantity = $trade['q']; $timestamp = $trade['T']; $maker = $trade['m'] ? 'true' : 'false'; $output[] = [ "price" => $price, "quantity" => $quantity, "timestamp" => $timestamp, "maker" => $maker, ]; } return $output; }
[ "private", "function", "tradesData", "(", "array", "$", "trades", ")", "{", "$", "output", "=", "[", "]", ";", "foreach", "(", "$", "trades", "as", "$", "trade", ")", "{", "$", "price", "=", "$", "trade", "[", "'p'", "]", ";", "$", "quantity", "=...
tradesData Convert aggTrades data into easier format $tradesData = $this->tradesData($trades); @param $trades array of trade information @return array easier format for trade information
[ "tradesData", "Convert", "aggTrades", "data", "into", "easier", "format" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1316-L1332
train
jaggedsoft/php-binance-api
php-binance-api.php
API.bookPriceData
private function bookPriceData(array $array) { $bookprices = []; foreach ($array as $obj) { $bookprices[$obj['symbol']] = [ "bid" => $obj['bidPrice'], "bids" => $obj['bidQty'], "ask" => $obj['askPrice'], "asks" => $obj['askQty'], ]; } return $bookprices; }
php
private function bookPriceData(array $array) { $bookprices = []; foreach ($array as $obj) { $bookprices[$obj['symbol']] = [ "bid" => $obj['bidPrice'], "bids" => $obj['bidQty'], "ask" => $obj['askPrice'], "asks" => $obj['askQty'], ]; } return $bookprices; }
[ "private", "function", "bookPriceData", "(", "array", "$", "array", ")", "{", "$", "bookprices", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "obj", ")", "{", "$", "bookprices", "[", "$", "obj", "[", "'symbol'", "]", "]", "=", "[", ...
bookPriceData Consolidates Book Prices into an easy to use object $bookPriceData = $this->bookPriceData($array); @param $array array book prices @return array easier format for book prices information
[ "bookPriceData", "Consolidates", "Book", "Prices", "into", "an", "easy", "to", "use", "object" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1342-L1354
train
jaggedsoft/php-binance-api
php-binance-api.php
API.cumulative
public function cumulative(array $depth) { $bids = []; $asks = []; $cumulative = 0; foreach ($depth['bids'] as $price => $quantity) { $cumulative += $quantity; $bids[] = [ $price, $cumulative, ]; } $cumulative = 0; foreach ($depth['asks'] as $price => $quantity) { $cumulative += $quantity; $asks[] = [ $price, $cumulative, ]; } return [ "bids" => $bids, "asks" => array_reverse($asks), ]; }
php
public function cumulative(array $depth) { $bids = []; $asks = []; $cumulative = 0; foreach ($depth['bids'] as $price => $quantity) { $cumulative += $quantity; $bids[] = [ $price, $cumulative, ]; } $cumulative = 0; foreach ($depth['asks'] as $price => $quantity) { $cumulative += $quantity; $asks[] = [ $price, $cumulative, ]; } return [ "bids" => $bids, "asks" => array_reverse($asks), ]; }
[ "public", "function", "cumulative", "(", "array", "$", "depth", ")", "{", "$", "bids", "=", "[", "]", ";", "$", "asks", "=", "[", "]", ";", "$", "cumulative", "=", "0", ";", "foreach", "(", "$", "depth", "[", "'bids'", "]", "as", "$", "price", ...
cumulative Converts depth cache into a cumulative array $cumulative = $api->cumulative($depth); @param $depth array cache array @return array cumulative depth cache
[ "cumulative", "Converts", "depth", "cache", "into", "a", "cumulative", "array" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1381-L1405
train
jaggedsoft/php-binance-api
php-binance-api.php
API.highstock
public function highstock(array $chart, bool $include_volume = false) { $array = []; foreach ($chart as $timestamp => $obj) { $line = [ $timestamp, floatval($obj['open']), floatval($obj['high']), floatval($obj['low']), floatval($obj['close']), ]; if ($include_volume) { $line[] = floatval($obj['volume']); } $array[] = $line; } return $array; }
php
public function highstock(array $chart, bool $include_volume = false) { $array = []; foreach ($chart as $timestamp => $obj) { $line = [ $timestamp, floatval($obj['open']), floatval($obj['high']), floatval($obj['low']), floatval($obj['close']), ]; if ($include_volume) { $line[] = floatval($obj['volume']); } $array[] = $line; } return $array; }
[ "public", "function", "highstock", "(", "array", "$", "chart", ",", "bool", "$", "include_volume", "=", "false", ")", "{", "$", "array", "=", "[", "]", ";", "foreach", "(", "$", "chart", "as", "$", "timestamp", "=>", "$", "obj", ")", "{", "$", "lin...
highstock Converts Chart Data into array for highstock & kline charts $highstock = $api->highstock($chart, $include_volume); @param $chart array @param $include_volume bool for inclusion of volume @return array highchart data
[ "highstock", "Converts", "Chart", "Data", "into", "array", "for", "highstock", "&", "kline", "charts" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1416-L1434
train
jaggedsoft/php-binance-api
php-binance-api.php
API.displayDepth
public function displayDepth(array $array) { $output = ''; foreach ([ 'asks', 'bids', ] as $type) { $entries = $array[$type]; if ($type === 'asks') { $entries = array_reverse($entries); } $output .= "{$type}:" . PHP_EOL; foreach ($entries as $price => $quantity) { $total = number_format($price * $quantity, 8, '.', ''); $quantity = str_pad(str_pad(number_format(rtrim($quantity, '.0')), 10, ' ', STR_PAD_LEFT), 15); $output .= "{$price} {$quantity} {$total}" . PHP_EOL; } // echo str_repeat('-', 32).PHP_EOL; } return $output; }
php
public function displayDepth(array $array) { $output = ''; foreach ([ 'asks', 'bids', ] as $type) { $entries = $array[$type]; if ($type === 'asks') { $entries = array_reverse($entries); } $output .= "{$type}:" . PHP_EOL; foreach ($entries as $price => $quantity) { $total = number_format($price * $quantity, 8, '.', ''); $quantity = str_pad(str_pad(number_format(rtrim($quantity, '.0')), 10, ' ', STR_PAD_LEFT), 15); $output .= "{$price} {$quantity} {$total}" . PHP_EOL; } // echo str_repeat('-', 32).PHP_EOL; } return $output; }
[ "public", "function", "displayDepth", "(", "array", "$", "array", ")", "{", "$", "output", "=", "''", ";", "foreach", "(", "[", "'asks'", ",", "'bids'", ",", "]", "as", "$", "type", ")", "{", "$", "entries", "=", "$", "array", "[", "$", "type", "...
displayDepth Formats nicely for console output $outputString = $api->displayDepth($array); @param $array array @return string of the depth information
[ "displayDepth", "Formats", "nicely", "for", "console", "output" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1476-L1497
train
jaggedsoft/php-binance-api
php-binance-api.php
API.depthData
private function depthData(string $symbol, array $json) { $bids = $asks = []; foreach ($json['bids'] as $obj) { $bids[$obj[0]] = $obj[1]; } foreach ($json['asks'] as $obj) { $asks[$obj[0]] = $obj[1]; } return $this->depthCache[$symbol] = [ "bids" => $bids, "asks" => $asks, ]; }
php
private function depthData(string $symbol, array $json) { $bids = $asks = []; foreach ($json['bids'] as $obj) { $bids[$obj[0]] = $obj[1]; } foreach ($json['asks'] as $obj) { $asks[$obj[0]] = $obj[1]; } return $this->depthCache[$symbol] = [ "bids" => $bids, "asks" => $asks, ]; }
[ "private", "function", "depthData", "(", "string", "$", "symbol", ",", "array", "$", "json", ")", "{", "$", "bids", "=", "$", "asks", "=", "[", "]", ";", "foreach", "(", "$", "json", "[", "'bids'", "]", "as", "$", "obj", ")", "{", "$", "bids", ...
depthData Formats depth data for nice display $array = $this->depthData($symbol, $json); @param $symbol string to display @param $json array of the depth infomration @return array of the depth information
[ "depthData", "Formats", "depth", "data", "for", "nice", "display" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1508-L1521
train
jaggedsoft/php-binance-api
php-binance-api.php
API.getTransfered
public function getTransfered() { $base = log($this->transfered, 1024); $suffixes = array( '', 'K', 'M', 'G', 'T', ); return round(pow(1024, $base - floor($base)), 2) . ' ' . $suffixes[floor($base)]; }
php
public function getTransfered() { $base = log($this->transfered, 1024); $suffixes = array( '', 'K', 'M', 'G', 'T', ); return round(pow(1024, $base - floor($base)), 2) . ' ' . $suffixes[floor($base)]; }
[ "public", "function", "getTransfered", "(", ")", "{", "$", "base", "=", "log", "(", "$", "this", "->", "transfered", ",", "1024", ")", ";", "$", "suffixes", "=", "array", "(", "''", ",", "'K'", ",", "'M'", ",", "'G'", ",", "'T'", ",", ")", ";", ...
getTransfered gets the total transfered in b,Kb,Mb,Gb $transfered = $api->getTransfered(); @return string showing the total transfered
[ "getTransfered", "gets", "the", "total", "transfered", "in", "b", "Kb", "Mb", "Gb" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1556-L1567
train
jaggedsoft/php-binance-api
php-binance-api.php
API.depthHandler
private function depthHandler(array $json) { $symbol = $json['s']; if ($json['u'] <= $this->info[$symbol]['firstUpdate']) { return; } foreach ($json['b'] as $bid) { $this->depthCache[$symbol]['bids'][$bid[0]] = $bid[1]; if ($bid[1] == "0.00000000") { unset($this->depthCache[$symbol]['bids'][$bid[0]]); } } foreach ($json['a'] as $ask) { $this->depthCache[$symbol]['asks'][$ask[0]] = $ask[1]; if ($ask[1] == "0.00000000") { unset($this->depthCache[$symbol]['asks'][$ask[0]]); } } }
php
private function depthHandler(array $json) { $symbol = $json['s']; if ($json['u'] <= $this->info[$symbol]['firstUpdate']) { return; } foreach ($json['b'] as $bid) { $this->depthCache[$symbol]['bids'][$bid[0]] = $bid[1]; if ($bid[1] == "0.00000000") { unset($this->depthCache[$symbol]['bids'][$bid[0]]); } } foreach ($json['a'] as $ask) { $this->depthCache[$symbol]['asks'][$ask[0]] = $ask[1]; if ($ask[1] == "0.00000000") { unset($this->depthCache[$symbol]['asks'][$ask[0]]); } } }
[ "private", "function", "depthHandler", "(", "array", "$", "json", ")", "{", "$", "symbol", "=", "$", "json", "[", "'s'", "]", ";", "if", "(", "$", "json", "[", "'u'", "]", "<=", "$", "this", "->", "info", "[", "$", "symbol", "]", "[", "'firstUpda...
depthHandler For WebSocket Depth Cache $this->depthHandler($json); @param $json array of depth bids and asks @return null
[ "depthHandler", "For", "WebSocket", "Depth", "Cache" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1607-L1628
train
jaggedsoft/php-binance-api
php-binance-api.php
API.chartHandler
private function chartHandler(string $symbol, string $interval, \stdClass $json) { if (!$this->info[$symbol][$interval]['firstOpen']) { // Wait for /kline to finish loading $this->chartQueue[$symbol][$interval][] = $json; return; } $chart = $json->k; $symbol = $json->s; $interval = $chart->i; $tick = $chart->t; if ($tick < $this->info[$symbol][$interval]['firstOpen']) { return; } // Filter out of sync data $open = $chart->o; $high = $chart->h; $low = $chart->l; $close = $chart->c; $volume = $chart->q; // +trades buyVolume assetVolume makerVolume $this->charts[$symbol][$interval][$tick] = [ "open" => $open, "high" => $high, "low" => $low, "close" => $close, "volume" => $volume, ]; }
php
private function chartHandler(string $symbol, string $interval, \stdClass $json) { if (!$this->info[$symbol][$interval]['firstOpen']) { // Wait for /kline to finish loading $this->chartQueue[$symbol][$interval][] = $json; return; } $chart = $json->k; $symbol = $json->s; $interval = $chart->i; $tick = $chart->t; if ($tick < $this->info[$symbol][$interval]['firstOpen']) { return; } // Filter out of sync data $open = $chart->o; $high = $chart->h; $low = $chart->l; $close = $chart->c; $volume = $chart->q; // +trades buyVolume assetVolume makerVolume $this->charts[$symbol][$interval][$tick] = [ "open" => $open, "high" => $high, "low" => $low, "close" => $close, "volume" => $volume, ]; }
[ "private", "function", "chartHandler", "(", "string", "$", "symbol", ",", "string", "$", "interval", ",", "\\", "stdClass", "$", "json", ")", "{", "if", "(", "!", "$", "this", "->", "info", "[", "$", "symbol", "]", "[", "$", "interval", "]", "[", "...
chartHandler For WebSocket Chart Cache $this->chartHandler($symbol, $interval, $json); @param $symbol string to sort @param $interval string time @param \stdClass $json object time @return null
[ "chartHandler", "For", "WebSocket", "Chart", "Cache" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1640-L1666
train
jaggedsoft/php-binance-api
php-binance-api.php
API.sortDepth
public function sortDepth(string $symbol, int $limit = 11) { $bids = $this->depthCache[$symbol]['bids']; $asks = $this->depthCache[$symbol]['asks']; krsort($bids); ksort($asks); return [ "asks" => array_slice($asks, 0, $limit, true), "bids" => array_slice($bids, 0, $limit, true), ]; }
php
public function sortDepth(string $symbol, int $limit = 11) { $bids = $this->depthCache[$symbol]['bids']; $asks = $this->depthCache[$symbol]['asks']; krsort($bids); ksort($asks); return [ "asks" => array_slice($asks, 0, $limit, true), "bids" => array_slice($bids, 0, $limit, true), ]; }
[ "public", "function", "sortDepth", "(", "string", "$", "symbol", ",", "int", "$", "limit", "=", "11", ")", "{", "$", "bids", "=", "$", "this", "->", "depthCache", "[", "$", "symbol", "]", "[", "'bids'", "]", ";", "$", "asks", "=", "$", "this", "-...
sortDepth Sorts depth data for display & getting highest bid and lowest ask $sorted = $api->sortDepth($symbol, $limit); @param $symbol string to sort @param $limit int depth @return null
[ "sortDepth", "Sorts", "depth", "data", "for", "display", "&", "getting", "highest", "bid", "and", "lowest", "ask" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1677-L1687
train
jaggedsoft/php-binance-api
php-binance-api.php
API.trades
public function trades($symbols, callable $callback) { if (!is_array($symbols)) { $symbols = [ $symbols, ]; } $loop = \React\EventLoop\Factory::create(); $react = new \React\Socket\Connector($loop); $connector = new \Ratchet\Client\Connector($loop, $react); foreach ($symbols as $symbol) { if (!isset($this->info[$symbol])) { $this->info[$symbol] = []; } // $this->info[$symbol]['tradesCallback'] = $callback; $endpoint = strtolower($symbol) . '@trades'; $this->subscriptions[$endpoint] = true; $connector($this->stream . strtolower($symbol) . '@aggTrade')->then(function ($ws) use ($callback, $symbol, $loop, $endpoint) { $ws->on('message', function ($data) use ($ws, $callback, $loop, $endpoint) { if ($this->subscriptions[$endpoint] === false) { //$this->subscriptions[$endpoint] = null; $loop->stop(); return; //return $ws->close(); } $json = json_decode($data, true); $symbol = $json['s']; $price = $json['p']; $quantity = $json['q']; $timestamp = $json['T']; $maker = $json['m'] ? 'true' : 'false'; $trades = [ "price" => $price, "quantity" => $quantity, "timestamp" => $timestamp, "maker" => $maker, ]; // $this->info[$symbol]['tradesCallback']($this, $symbol, $trades); call_user_func($callback, $this, $symbol, $trades); }); $ws->on('close', function ($code = null, $reason = null) use ($symbol, $loop) { // WPCS: XSS OK. echo "trades({$symbol}) WebSocket Connection closed! ({$code} - {$reason})" . PHP_EOL; $loop->stop(); }); }, function ($e) use ($loop, $symbol) { // WPCS: XSS OK. echo "trades({$symbol}) Could not connect: {$e->getMessage()}" . PHP_EOL; $loop->stop(); }); } $loop->run(); }
php
public function trades($symbols, callable $callback) { if (!is_array($symbols)) { $symbols = [ $symbols, ]; } $loop = \React\EventLoop\Factory::create(); $react = new \React\Socket\Connector($loop); $connector = new \Ratchet\Client\Connector($loop, $react); foreach ($symbols as $symbol) { if (!isset($this->info[$symbol])) { $this->info[$symbol] = []; } // $this->info[$symbol]['tradesCallback'] = $callback; $endpoint = strtolower($symbol) . '@trades'; $this->subscriptions[$endpoint] = true; $connector($this->stream . strtolower($symbol) . '@aggTrade')->then(function ($ws) use ($callback, $symbol, $loop, $endpoint) { $ws->on('message', function ($data) use ($ws, $callback, $loop, $endpoint) { if ($this->subscriptions[$endpoint] === false) { //$this->subscriptions[$endpoint] = null; $loop->stop(); return; //return $ws->close(); } $json = json_decode($data, true); $symbol = $json['s']; $price = $json['p']; $quantity = $json['q']; $timestamp = $json['T']; $maker = $json['m'] ? 'true' : 'false'; $trades = [ "price" => $price, "quantity" => $quantity, "timestamp" => $timestamp, "maker" => $maker, ]; // $this->info[$symbol]['tradesCallback']($this, $symbol, $trades); call_user_func($callback, $this, $symbol, $trades); }); $ws->on('close', function ($code = null, $reason = null) use ($symbol, $loop) { // WPCS: XSS OK. echo "trades({$symbol}) WebSocket Connection closed! ({$code} - {$reason})" . PHP_EOL; $loop->stop(); }); }, function ($e) use ($loop, $symbol) { // WPCS: XSS OK. echo "trades({$symbol}) Could not connect: {$e->getMessage()}" . PHP_EOL; $loop->stop(); }); } $loop->run(); }
[ "public", "function", "trades", "(", "$", "symbols", ",", "callable", "$", "callback", ")", "{", "if", "(", "!", "is_array", "(", "$", "symbols", ")", ")", "{", "$", "symbols", "=", "[", "$", "symbols", ",", "]", ";", "}", "$", "loop", "=", "\\",...
trades Trades WebSocket Endpoint $api->trades(["BNBBTC"], function($api, $symbol, $trades) { echo "{$symbol} trades update".PHP_EOL; print_r($trades); }); @param $symbols @param $callback callable closure @return null
[ "trades", "Trades", "WebSocket", "Endpoint" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1790-L1845
train
jaggedsoft/php-binance-api
php-binance-api.php
API.ticker
public function ticker($symbol, callable $callback) { $endpoint = $symbol ? strtolower($symbol) . '@ticker' : '!ticker@arr'; $this->subscriptions[$endpoint] = true; // @codeCoverageIgnoreStart // phpunit can't cover async function \Ratchet\Client\connect($this->stream . $endpoint)->then(function ($ws) use ($callback, $symbol, $endpoint) { $ws->on('message', function ($data) use ($ws, $callback, $symbol, $endpoint) { if ($this->subscriptions[$endpoint] === false) { //$this->subscriptions[$endpoint] = null; $ws->close(); return; //return $ws->close(); } $json = json_decode($data); if ($symbol) { call_user_func($callback, $this, $symbol, $this->tickerStreamHandler($json)); } else { foreach ($json as $obj) { $return = $this->tickerStreamHandler($obj); $symbol = $return['symbol']; call_user_func($callback, $this, $symbol, $return); } } }); $ws->on('close', function ($code = null, $reason = null) { // WPCS: XSS OK. echo "ticker: WebSocket Connection closed! ({$code} - {$reason})" . PHP_EOL; }); }, function ($e) { // WPCS: XSS OK. echo "ticker: Could not connect: {$e->getMessage()}" . PHP_EOL; }); // @codeCoverageIgnoreEnd }
php
public function ticker($symbol, callable $callback) { $endpoint = $symbol ? strtolower($symbol) . '@ticker' : '!ticker@arr'; $this->subscriptions[$endpoint] = true; // @codeCoverageIgnoreStart // phpunit can't cover async function \Ratchet\Client\connect($this->stream . $endpoint)->then(function ($ws) use ($callback, $symbol, $endpoint) { $ws->on('message', function ($data) use ($ws, $callback, $symbol, $endpoint) { if ($this->subscriptions[$endpoint] === false) { //$this->subscriptions[$endpoint] = null; $ws->close(); return; //return $ws->close(); } $json = json_decode($data); if ($symbol) { call_user_func($callback, $this, $symbol, $this->tickerStreamHandler($json)); } else { foreach ($json as $obj) { $return = $this->tickerStreamHandler($obj); $symbol = $return['symbol']; call_user_func($callback, $this, $symbol, $return); } } }); $ws->on('close', function ($code = null, $reason = null) { // WPCS: XSS OK. echo "ticker: WebSocket Connection closed! ({$code} - {$reason})" . PHP_EOL; }); }, function ($e) { // WPCS: XSS OK. echo "ticker: Could not connect: {$e->getMessage()}" . PHP_EOL; }); // @codeCoverageIgnoreEnd }
[ "public", "function", "ticker", "(", "$", "symbol", ",", "callable", "$", "callback", ")", "{", "$", "endpoint", "=", "$", "symbol", "?", "strtolower", "(", "$", "symbol", ")", ".", "'@ticker'", ":", "'!ticker@arr'", ";", "$", "this", "->", "subscription...
ticker pulls 24h price change statistics via WebSocket $api->ticker(false, function($api, $symbol, $ticker) { print_r($ticker); }); @param $symbol string optional symbol or false @param $callback callable closure @return null
[ "ticker", "pulls", "24h", "price", "change", "statistics", "via", "WebSocket" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L1858-L1892
train
jaggedsoft/php-binance-api
php-binance-api.php
API.keepAlive
public function keepAlive() { $loop = \React\EventLoop\Factory::create(); $loop->addPeriodicTimer(30, function () { $listenKey = $this->listenKey; $this->httpRequest("v1/userDataStream?listenKey={$listenKey}", "PUT", []); }); $loop->run(); }
php
public function keepAlive() { $loop = \React\EventLoop\Factory::create(); $loop->addPeriodicTimer(30, function () { $listenKey = $this->listenKey; $this->httpRequest("v1/userDataStream?listenKey={$listenKey}", "PUT", []); }); $loop->run(); }
[ "public", "function", "keepAlive", "(", ")", "{", "$", "loop", "=", "\\", "React", "\\", "EventLoop", "\\", "Factory", "::", "create", "(", ")", ";", "$", "loop", "->", "addPeriodicTimer", "(", "30", ",", "function", "(", ")", "{", "$", "listenKey", ...
keepAlive Keep-alive function for userDataStream $api->keepAlive(); @return null
[ "keepAlive", "Keep", "-", "alive", "function", "for", "userDataStream" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L2050-L2058
train
jaggedsoft/php-binance-api
php-binance-api.php
API.userData
public function userData(&$balance_callback, &$execution_callback = false) { $response = $this->httpRequest("v1/userDataStream", "POST", []); $this->listenKey = $response['listenKey']; $this->info['balanceCallback'] = $balance_callback; $this->info['executionCallback'] = $execution_callback; $this->subscriptions['@userdata'] = true; // @codeCoverageIgnoreStart // phpunit can't cover async function \Ratchet\Client\connect($this->stream . $this->listenKey)->then(function ($ws) { $ws->on('message', function ($data) use ($ws) { if ($this->subscriptions['@userdata'] === false) { //$this->subscriptions[$endpoint] = null; $ws->close(); return; //return $ws->close(); } $json = json_decode($data); $type = $json->e; if ($type === "outboundAccountInfo") { $balances = $this->balanceHandler($json->B); $this->info['balanceCallback']($this, $balances); } elseif ($type === "executionReport") { $report = $this->executionHandler($json); if ($this->info['executionCallback']) { $this->info['executionCallback']($this, $report); } } }); $ws->on('close', function ($code = null, $reason = null) { // WPCS: XSS OK. echo "userData: WebSocket Connection closed! ({$code} - {$reason})" . PHP_EOL; }); }, function ($e) { // WPCS: XSS OK. echo "userData: Could not connect: {$e->getMessage()}" . PHP_EOL; }); // @codeCoverageIgnoreEnd }
php
public function userData(&$balance_callback, &$execution_callback = false) { $response = $this->httpRequest("v1/userDataStream", "POST", []); $this->listenKey = $response['listenKey']; $this->info['balanceCallback'] = $balance_callback; $this->info['executionCallback'] = $execution_callback; $this->subscriptions['@userdata'] = true; // @codeCoverageIgnoreStart // phpunit can't cover async function \Ratchet\Client\connect($this->stream . $this->listenKey)->then(function ($ws) { $ws->on('message', function ($data) use ($ws) { if ($this->subscriptions['@userdata'] === false) { //$this->subscriptions[$endpoint] = null; $ws->close(); return; //return $ws->close(); } $json = json_decode($data); $type = $json->e; if ($type === "outboundAccountInfo") { $balances = $this->balanceHandler($json->B); $this->info['balanceCallback']($this, $balances); } elseif ($type === "executionReport") { $report = $this->executionHandler($json); if ($this->info['executionCallback']) { $this->info['executionCallback']($this, $report); } } }); $ws->on('close', function ($code = null, $reason = null) { // WPCS: XSS OK. echo "userData: WebSocket Connection closed! ({$code} - {$reason})" . PHP_EOL; }); }, function ($e) { // WPCS: XSS OK. echo "userData: Could not connect: {$e->getMessage()}" . PHP_EOL; }); // @codeCoverageIgnoreEnd }
[ "public", "function", "userData", "(", "&", "$", "balance_callback", ",", "&", "$", "execution_callback", "=", "false", ")", "{", "$", "response", "=", "$", "this", "->", "httpRequest", "(", "\"v1/userDataStream\"", ",", "\"POST\"", ",", "[", "]", ")", ";"...
userData Issues userDataStream token and keepalive, subscribes to userData WebSocket $balance_update = function($api, $balances) { print_r($balances); echo "Balance update".PHP_EOL; }; $order_update = function($api, $report) { echo "Order update".PHP_EOL; print_r($report); $price = $report['price']; $quantity = $report['quantity']; $symbol = $report['symbol']; $side = $report['side']; $orderType = $report['orderType']; $orderId = $report['orderId']; $orderStatus = $report['orderStatus']; $executionType = $report['orderStatus']; if( $executionType == "NEW" ) { if( $executionType == "REJECTED" ) { echo "Order Failed! Reason: {$report['rejectReason']}".PHP_EOL; } echo "{$symbol} {$side} {$orderType} ORDER #{$orderId} ({$orderStatus})".PHP_EOL; echo "..price: {$price}, quantity: {$quantity}".PHP_EOL; return; } //NEW, CANCELED, REPLACED, REJECTED, TRADE, EXPIRED echo "{$symbol} {$side} {$executionType} {$orderType} ORDER #{$orderId}".PHP_EOL; }; $api->userData($balance_update, $order_update); @param $balance_callback callable function @param bool $execution_callback callable function @return null @throws \Exception
[ "userData", "Issues", "userDataStream", "token", "and", "keepalive", "subscribes", "to", "userData", "WebSocket" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L2098-L2137
train
jaggedsoft/php-binance-api
php-binance-api.php
API.miniTicker
public function miniTicker(callable $callback) { $endpoint = '@miniticker'; $this->subscriptions[$endpoint] = true; // @codeCoverageIgnoreStart // phpunit can't cover async function \Ratchet\Client\connect($this->stream . '!miniTicker@arr')->then(function ($ws) use ($callback, $endpoint) { $ws->on('message', function ($data) use ($ws, $callback, $endpoint) { if ($this->subscriptions[$endpoint] === false) { //$this->subscriptions[$endpoint] = null; $ws->close(); return; //return $ws->close(); } $json = json_decode($data, true); $markets = []; foreach ($json as $obj) { $markets[] = [ "symbol" => $obj['s'], "close" => $obj['c'], "open" => $obj['o'], "high" => $obj['h'], "low" => $obj['l'], "volume" => $obj['v'], "quoteVolume" => $obj['q'], "eventTime" => $obj['E'], ]; } call_user_func($callback, $this, $markets); }); $ws->on('close', function ($code = null, $reason = null) { // WPCS: XSS OK. echo "miniticker: WebSocket Connection closed! ({$code} - {$reason})" . PHP_EOL; }); }, function ($e) { // WPCS: XSS OK. echo "miniticker: Could not connect: {$e->getMessage()}" . PHP_EOL; }); // @codeCoverageIgnoreEnd }
php
public function miniTicker(callable $callback) { $endpoint = '@miniticker'; $this->subscriptions[$endpoint] = true; // @codeCoverageIgnoreStart // phpunit can't cover async function \Ratchet\Client\connect($this->stream . '!miniTicker@arr')->then(function ($ws) use ($callback, $endpoint) { $ws->on('message', function ($data) use ($ws, $callback, $endpoint) { if ($this->subscriptions[$endpoint] === false) { //$this->subscriptions[$endpoint] = null; $ws->close(); return; //return $ws->close(); } $json = json_decode($data, true); $markets = []; foreach ($json as $obj) { $markets[] = [ "symbol" => $obj['s'], "close" => $obj['c'], "open" => $obj['o'], "high" => $obj['h'], "low" => $obj['l'], "volume" => $obj['v'], "quoteVolume" => $obj['q'], "eventTime" => $obj['E'], ]; } call_user_func($callback, $this, $markets); }); $ws->on('close', function ($code = null, $reason = null) { // WPCS: XSS OK. echo "miniticker: WebSocket Connection closed! ({$code} - {$reason})" . PHP_EOL; }); }, function ($e) { // WPCS: XSS OK. echo "miniticker: Could not connect: {$e->getMessage()}" . PHP_EOL; }); // @codeCoverageIgnoreEnd }
[ "public", "function", "miniTicker", "(", "callable", "$", "callback", ")", "{", "$", "endpoint", "=", "'@miniticker'", ";", "$", "this", "->", "subscriptions", "[", "$", "endpoint", "]", "=", "true", ";", "// @codeCoverageIgnoreStart", "// phpunit can't cover asyn...
miniTicker Get miniTicker for all symbols $api->miniTicker(function($api, $ticker) { print_r($ticker); }); @param $callback callable function closer that takes 2 arguments, $pai and $ticker data @return null
[ "miniTicker", "Get", "miniTicker", "for", "all", "symbols" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L2149-L2188
train
jaggedsoft/php-binance-api
php-binance-api.php
API.downloadCurlCaBundle
private function downloadCurlCaBundle() { $output_filename = getcwd() . "/ca.pem"; if (is_writable(getcwd()) === false) { die(getcwd() . " folder is not writeable, plese check your permissions"); } $host = "https://curl.haxx.se/ca/cacert.pem"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $host); curl_setopt($curl, CURLOPT_VERBOSE, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // proxy settings if (is_array($this->proxyConf)) { curl_setopt($curl, CURLOPT_PROXY, $this->getProxyUriString()); if (isset($this->proxyConf['user']) && isset($this->proxyConf['pass'])) { curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxyConf['user'] . ':' . $this->proxyConf['pass']); } } $result = curl_exec($curl); curl_close($curl); if ($result === false) { echo "Unable to to download the CA bundle $host" . PHP_EOL; return; } $fp = fopen($output_filename, 'w'); if ($fp === false) { echo "Unable to write $output_filename, please check permissions on folder" . PHP_EOL; return; } fwrite($fp, $result); fclose($fp); }
php
private function downloadCurlCaBundle() { $output_filename = getcwd() . "/ca.pem"; if (is_writable(getcwd()) === false) { die(getcwd() . " folder is not writeable, plese check your permissions"); } $host = "https://curl.haxx.se/ca/cacert.pem"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $host); curl_setopt($curl, CURLOPT_VERBOSE, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // proxy settings if (is_array($this->proxyConf)) { curl_setopt($curl, CURLOPT_PROXY, $this->getProxyUriString()); if (isset($this->proxyConf['user']) && isset($this->proxyConf['pass'])) { curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxyConf['user'] . ':' . $this->proxyConf['pass']); } } $result = curl_exec($curl); curl_close($curl); if ($result === false) { echo "Unable to to download the CA bundle $host" . PHP_EOL; return; } $fp = fopen($output_filename, 'w'); if ($fp === false) { echo "Unable to write $output_filename, please check permissions on folder" . PHP_EOL; return; } fwrite($fp, $result); fclose($fp); }
[ "private", "function", "downloadCurlCaBundle", "(", ")", "{", "$", "output_filename", "=", "getcwd", "(", ")", ".", "\"/ca.pem\"", ";", "if", "(", "is_writable", "(", "getcwd", "(", ")", ")", "===", "false", ")", "{", "die", "(", "getcwd", "(", ")", "....
Due to ongoing issues with out of date wamp CA bundles This function downloads ca bundle for curl website and uses it as part of the curl options
[ "Due", "to", "ongoing", "issues", "with", "out", "of", "date", "wamp", "CA", "bundles", "This", "function", "downloads", "ca", "bundle", "for", "curl", "website", "and", "uses", "it", "as", "part", "of", "the", "curl", "options" ]
1d22afb4bcf60d2321403433b18726ba1e50380d
https://github.com/jaggedsoft/php-binance-api/blob/1d22afb4bcf60d2321403433b18726ba1e50380d/php-binance-api.php#L2195-L2237
train
yajra/laravel-datatables-html
src/Html/HasOptions.php
HasOptions.orderBy
public function orderBy($index, $direction = 'desc') { if ($direction != 'desc') { $direction = 'asc'; } if (is_array($index)) { $this->attributes['order'][] = $index; } else { $this->attributes['order'][] = [$index, $direction]; } return $this; }
php
public function orderBy($index, $direction = 'desc') { if ($direction != 'desc') { $direction = 'asc'; } if (is_array($index)) { $this->attributes['order'][] = $index; } else { $this->attributes['order'][] = [$index, $direction]; } return $this; }
[ "public", "function", "orderBy", "(", "$", "index", ",", "$", "direction", "=", "'desc'", ")", "{", "if", "(", "$", "direction", "!=", "'desc'", ")", "{", "$", "direction", "=", "'asc'", ";", "}", "if", "(", "is_array", "(", "$", "index", ")", ")",...
Order option builder. @param int|array $index @param string $direction @return $this @see https://datatables.net/reference/option/order
[ "Order", "option", "builder", "." ]
80f340f6b659bed6f0fa19bc26ce9474ab663d17
https://github.com/yajra/laravel-datatables-html/blob/80f340f6b659bed6f0fa19bc26ce9474ab663d17/src/Html/HasOptions.php#L151-L164
train
yajra/laravel-datatables-html
src/Html/HasOptions.php
HasOptions.orderByFixed
public function orderByFixed($index, $direction = 'desc') { if ($direction != 'desc') { $direction = 'asc'; } if (is_array($index)) { $this->attributes['orderFixed'][] = $index; } else { $this->attributes['orderFixed'][] = [$index, $direction]; } return $this; }
php
public function orderByFixed($index, $direction = 'desc') { if ($direction != 'desc') { $direction = 'asc'; } if (is_array($index)) { $this->attributes['orderFixed'][] = $index; } else { $this->attributes['orderFixed'][] = [$index, $direction]; } return $this; }
[ "public", "function", "orderByFixed", "(", "$", "index", ",", "$", "direction", "=", "'desc'", ")", "{", "if", "(", "$", "direction", "!=", "'desc'", ")", "{", "$", "direction", "=", "'asc'", ";", "}", "if", "(", "is_array", "(", "$", "index", ")", ...
Order Fixed option builder. @param int|array $index @param string $direction @return $this @see https://datatables.net/reference/option/orderFixed
[ "Order", "Fixed", "option", "builder", "." ]
80f340f6b659bed6f0fa19bc26ce9474ab663d17
https://github.com/yajra/laravel-datatables-html/blob/80f340f6b659bed6f0fa19bc26ce9474ab663d17/src/Html/HasOptions.php#L174-L187
train
yajra/laravel-datatables-html
src/Html/Options/HasData.php
HasData.postAjax
public function postAjax($attributes = '') { if (! is_array($attributes)) { $attributes = ['url' => (string) $attributes]; } unset($attributes['method']); array_set($attributes, 'type', 'POST'); array_set($attributes, 'headers.X-HTTP-Method-Override', 'GET'); return $this->ajax($attributes); }
php
public function postAjax($attributes = '') { if (! is_array($attributes)) { $attributes = ['url' => (string) $attributes]; } unset($attributes['method']); array_set($attributes, 'type', 'POST'); array_set($attributes, 'headers.X-HTTP-Method-Override', 'GET'); return $this->ajax($attributes); }
[ "public", "function", "postAjax", "(", "$", "attributes", "=", "''", ")", "{", "if", "(", "!", "is_array", "(", "$", "attributes", ")", ")", "{", "$", "attributes", "=", "[", "'url'", "=>", "(", "string", ")", "$", "attributes", "]", ";", "}", "uns...
Setup "ajax" parameter with POST method. @param string|array $attributes @return $this
[ "Setup", "ajax", "parameter", "with", "POST", "method", "." ]
80f340f6b659bed6f0fa19bc26ce9474ab663d17
https://github.com/yajra/laravel-datatables-html/blob/80f340f6b659bed6f0fa19bc26ce9474ab663d17/src/Html/Options/HasData.php#L36-L47
train
yajra/laravel-datatables-html
src/Html/Options/HasData.php
HasData.minifiedAjax
public function minifiedAjax($url = '', $script = null, $data = [], $ajaxParameters = []) { $this->ajax = []; $appendData = $this->makeDataScript($data); $this->ajax['url'] = $url; $this->ajax['type'] = 'GET'; if (isset($this->attributes['serverSide']) ? $this->attributes['serverSide'] : true) { $this->ajax['data'] = 'function(data) { for (var i = 0, len = data.columns.length; i < len; i++) { if (!data.columns[i].search.value) delete data.columns[i].search; if (data.columns[i].searchable === true) delete data.columns[i].searchable; if (data.columns[i].orderable === true) delete data.columns[i].orderable; if (data.columns[i].data === data.columns[i].name) delete data.columns[i].name; } delete data.search.regex;'; } else { $this->ajax['data'] = 'function(data){'; } if ($appendData) { $this->ajax['data'] .= $appendData; } if ($script) { $this->ajax['data'] .= $script; } $this->ajax['data'] .= '}'; $this->ajax = array_merge($this->ajax, $ajaxParameters); return $this; }
php
public function minifiedAjax($url = '', $script = null, $data = [], $ajaxParameters = []) { $this->ajax = []; $appendData = $this->makeDataScript($data); $this->ajax['url'] = $url; $this->ajax['type'] = 'GET'; if (isset($this->attributes['serverSide']) ? $this->attributes['serverSide'] : true) { $this->ajax['data'] = 'function(data) { for (var i = 0, len = data.columns.length; i < len; i++) { if (!data.columns[i].search.value) delete data.columns[i].search; if (data.columns[i].searchable === true) delete data.columns[i].searchable; if (data.columns[i].orderable === true) delete data.columns[i].orderable; if (data.columns[i].data === data.columns[i].name) delete data.columns[i].name; } delete data.search.regex;'; } else { $this->ajax['data'] = 'function(data){'; } if ($appendData) { $this->ajax['data'] .= $appendData; } if ($script) { $this->ajax['data'] .= $script; } $this->ajax['data'] .= '}'; $this->ajax = array_merge($this->ajax, $ajaxParameters); return $this; }
[ "public", "function", "minifiedAjax", "(", "$", "url", "=", "''", ",", "$", "script", "=", "null", ",", "$", "data", "=", "[", "]", ",", "$", "ajaxParameters", "=", "[", "]", ")", "{", "$", "this", "->", "ajax", "=", "[", "]", ";", "$", "append...
Minify ajax url generated when using get request by deleting unnecessary url params. @param string $url @param string $script @param array $data @param array $ajaxParameters @return $this
[ "Minify", "ajax", "url", "generated", "when", "using", "get", "request", "by", "deleting", "unnecessary", "url", "params", "." ]
80f340f6b659bed6f0fa19bc26ce9474ab663d17
https://github.com/yajra/laravel-datatables-html/blob/80f340f6b659bed6f0fa19bc26ce9474ab663d17/src/Html/Options/HasData.php#L73-L106
train
yajra/laravel-datatables-html
src/Html/Options/HasData.php
HasData.getAjaxUrl
public function getAjaxUrl() { if (is_array($this->ajax)) { return $this->ajax['url'] ?: url()->current(); } return $this->ajax ?: url()->current(); }
php
public function getAjaxUrl() { if (is_array($this->ajax)) { return $this->ajax['url'] ?: url()->current(); } return $this->ajax ?: url()->current(); }
[ "public", "function", "getAjaxUrl", "(", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "ajax", ")", ")", "{", "return", "$", "this", "->", "ajax", "[", "'url'", "]", "?", ":", "url", "(", ")", "->", "current", "(", ")", ";", "}", "re...
Get ajax url. @return array|mixed|string
[ "Get", "ajax", "url", "." ]
80f340f6b659bed6f0fa19bc26ce9474ab663d17
https://github.com/yajra/laravel-datatables-html/blob/80f340f6b659bed6f0fa19bc26ce9474ab663d17/src/Html/Options/HasData.php#L113-L120
train
yajra/laravel-datatables-html
src/Html/Options/Plugins/Buttons.php
Buttons.buttons
public function buttons(...$buttons) { foreach ($buttons as $button) { $this->attributes['buttons'][] = $button instanceof Arrayable ? $button->toArray() : $button; } return $this; }
php
public function buttons(...$buttons) { foreach ($buttons as $button) { $this->attributes['buttons'][] = $button instanceof Arrayable ? $button->toArray() : $button; } return $this; }
[ "public", "function", "buttons", "(", "...", "$", "buttons", ")", "{", "foreach", "(", "$", "buttons", "as", "$", "button", ")", "{", "$", "this", "->", "attributes", "[", "'buttons'", "]", "[", "]", "=", "$", "button", "instanceof", "Arrayable", "?", ...
Attach multiple buttons to builder. @param mixed ...$buttons @return $this @see https://www.datatables.net/extensions/buttons/
[ "Attach", "multiple", "buttons", "to", "builder", "." ]
80f340f6b659bed6f0fa19bc26ce9474ab663d17
https://github.com/yajra/laravel-datatables-html/blob/80f340f6b659bed6f0fa19bc26ce9474ab663d17/src/Html/Options/Plugins/Buttons.php#L22-L29
train
yajra/laravel-datatables-html
src/Html/Options/HasColumns.php
HasColumns.columns
public function columns(array $columns) { $this->collection = new Collection; foreach ($columns as $key => $value) { if (! is_a($value, Column::class)) { if (is_array($value)) { $attributes = array_merge( [ 'name' => $value['name'] ?? $value['data'] ?? $key, 'data' => $value['data'] ?? $key, ], $this->setTitle($key, $value) ); } else { $attributes = [ 'name' => $value, 'data' => $value, 'title' => $this->getQualifiedTitle($value), ]; } $this->collection->push(new Column($attributes)); } else { $this->collection->push($value); } } return $this; }
php
public function columns(array $columns) { $this->collection = new Collection; foreach ($columns as $key => $value) { if (! is_a($value, Column::class)) { if (is_array($value)) { $attributes = array_merge( [ 'name' => $value['name'] ?? $value['data'] ?? $key, 'data' => $value['data'] ?? $key, ], $this->setTitle($key, $value) ); } else { $attributes = [ 'name' => $value, 'data' => $value, 'title' => $this->getQualifiedTitle($value), ]; } $this->collection->push(new Column($attributes)); } else { $this->collection->push($value); } } return $this; }
[ "public", "function", "columns", "(", "array", "$", "columns", ")", "{", "$", "this", "->", "collection", "=", "new", "Collection", ";", "foreach", "(", "$", "columns", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "is_a", "(", "$...
Set columns option value. @param array $columns @return $this @see https://datatables.net/reference/option/columns
[ "Set", "columns", "option", "value", "." ]
80f340f6b659bed6f0fa19bc26ce9474ab663d17
https://github.com/yajra/laravel-datatables-html/blob/80f340f6b659bed6f0fa19bc26ce9474ab663d17/src/Html/Options/HasColumns.php#L37-L66
train
yajra/laravel-datatables-html
src/Html/Options/HasColumns.php
HasColumns.setTitle
public function setTitle($title, array $attributes) { if (! isset($attributes['title'])) { $attributes['title'] = $this->getQualifiedTitle($title); } return $attributes; }
php
public function setTitle($title, array $attributes) { if (! isset($attributes['title'])) { $attributes['title'] = $this->getQualifiedTitle($title); } return $attributes; }
[ "public", "function", "setTitle", "(", "$", "title", ",", "array", "$", "attributes", ")", "{", "if", "(", "!", "isset", "(", "$", "attributes", "[", "'title'", "]", ")", ")", "{", "$", "attributes", "[", "'title'", "]", "=", "$", "this", "->", "ge...
Set title attribute of an array if not set. @param string $title @param array $attributes @return array
[ "Set", "title", "attribute", "of", "an", "array", "if", "not", "set", "." ]
80f340f6b659bed6f0fa19bc26ce9474ab663d17
https://github.com/yajra/laravel-datatables-html/blob/80f340f6b659bed6f0fa19bc26ce9474ab663d17/src/Html/Options/HasColumns.php#L75-L82
train
yajra/laravel-datatables-html
src/Html/Options/HasColumns.php
HasColumns.removeColumn
public function removeColumn(...$names) { foreach ($names as $name) { $this->collection = $this->collection->filter(function (Column $column) use ($name) { return $column->name !== $name; })->flatten(); } return $this; }
php
public function removeColumn(...$names) { foreach ($names as $name) { $this->collection = $this->collection->filter(function (Column $column) use ($name) { return $column->name !== $name; })->flatten(); } return $this; }
[ "public", "function", "removeColumn", "(", "...", "$", "names", ")", "{", "foreach", "(", "$", "names", "as", "$", "name", ")", "{", "$", "this", "->", "collection", "=", "$", "this", "->", "collection", "->", "filter", "(", "function", "(", "Column", ...
Remove column by name. @param array $names @return $this
[ "Remove", "column", "by", "name", "." ]
80f340f6b659bed6f0fa19bc26ce9474ab663d17
https://github.com/yajra/laravel-datatables-html/blob/80f340f6b659bed6f0fa19bc26ce9474ab663d17/src/Html/Options/HasColumns.php#L163-L172
train