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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
vitalets/x-editable-yii | EditableConfig.php | EditableConfig.init | public function init()
{
parent::init();
if(empty($this->defaults)) $this->defaults = array();
//copy mode from first level config to defaults (for compability)
if(empty($this->defaults['mode'])) $this->defaults['mode'] = $this->mode;
$defaults = CJavaScript::encode($this->defaults);
Yii::app()->getClientScript()->registerScript(
'editable-defaults', 'if($.fn.editable) $.extend($.fn.editable.defaults, '.$defaults.');'
);
} | php | public function init()
{
parent::init();
if(empty($this->defaults)) $this->defaults = array();
//copy mode from first level config to defaults (for compability)
if(empty($this->defaults['mode'])) $this->defaults['mode'] = $this->mode;
$defaults = CJavaScript::encode($this->defaults);
Yii::app()->getClientScript()->registerScript(
'editable-defaults', 'if($.fn.editable) $.extend($.fn.editable.defaults, '.$defaults.');'
);
} | [
"public",
"function",
"init",
"(",
")",
"{",
"parent",
"::",
"init",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"defaults",
")",
")",
"$",
"this",
"->",
"defaults",
"=",
"array",
"(",
")",
";",
"//copy mode from first level config to defa... | initializes editable component and sets defaults | [
"initializes",
"editable",
"component",
"and",
"sets",
"defaults"
] | 06faae330f3bdb150cf33dfb7e7e0c731e376647 | https://github.com/vitalets/x-editable-yii/blob/06faae330f3bdb150cf33dfb7e7e0c731e376647/EditableConfig.php#L41-L51 | train |
sskaje/mqtt | mqtt/MQTT.php | MQTT.publish_sync | public function publish_sync($topic, $message, $qos=0, $retain=0, &$msgid=0)
{
# set default call_handler
# initial dup = 0
$dup = 0;
# initial msgid = 0
$msgid = 0;
# non blocking
$this->socket->set_non_blocking();
$r = $this->do_publish($topic, $message, $qos, $retain, $msgid, $dup);
if ($qos == 0) {
return $r['ret'];
}
# loop
do {
$r = $this->handle_message();
if (!$r) {
usleep(10000);
continue;
}
$finished = $qos == 1 ?
$this->cmdstore->isEmpty(Message::PUBACK, $msgid) :
(
$this->cmdstore->isEmpty(Message::PUBREC, $msgid) &&
$this->cmdstore->isEmpty(Message::PUBCOMP, $msgid)
);
if (!$finished) {
# retry publish
$this->handle_publish($msgid);
} else {
return true;
}
} while (true);
return false;
} | php | public function publish_sync($topic, $message, $qos=0, $retain=0, &$msgid=0)
{
# set default call_handler
# initial dup = 0
$dup = 0;
# initial msgid = 0
$msgid = 0;
# non blocking
$this->socket->set_non_blocking();
$r = $this->do_publish($topic, $message, $qos, $retain, $msgid, $dup);
if ($qos == 0) {
return $r['ret'];
}
# loop
do {
$r = $this->handle_message();
if (!$r) {
usleep(10000);
continue;
}
$finished = $qos == 1 ?
$this->cmdstore->isEmpty(Message::PUBACK, $msgid) :
(
$this->cmdstore->isEmpty(Message::PUBREC, $msgid) &&
$this->cmdstore->isEmpty(Message::PUBCOMP, $msgid)
);
if (!$finished) {
# retry publish
$this->handle_publish($msgid);
} else {
return true;
}
} while (true);
return false;
} | [
"public",
"function",
"publish_sync",
"(",
"$",
"topic",
",",
"$",
"message",
",",
"$",
"qos",
"=",
"0",
",",
"$",
"retain",
"=",
"0",
",",
"&",
"$",
"msgid",
"=",
"0",
")",
"{",
"# set default call_handler",
"# initial dup = 0",
"$",
"dup",
"=",
"0",
... | Publish Message to topic synchronized
@param string $topic
@param string $message
@param int $qos
@param int $retain
@param int & $msgid
@return array|bool
@throws Exception | [
"Publish",
"Message",
"to",
"topic",
"synchronized"
] | 38cf01a177ed8e6ff387cdefcf11ba42594e330f | https://github.com/sskaje/mqtt/blob/38cf01a177ed8e6ff387cdefcf11ba42594e330f/mqtt/MQTT.php#L446-L489 | train |
sskaje/mqtt | mqtt/MQTT.php | MQTT.message_write | protected function message_write(Base $object, & $length=0)
{
Debug::Log(Debug::DEBUG, 'Message write: message_type='.Message::$name[$object->getMessageType()]);
$length = 0;
$message = $object->build($length);
$bytes_written = $this->socket->write($message, $length);
return $bytes_written;
} | php | protected function message_write(Base $object, & $length=0)
{
Debug::Log(Debug::DEBUG, 'Message write: message_type='.Message::$name[$object->getMessageType()]);
$length = 0;
$message = $object->build($length);
$bytes_written = $this->socket->write($message, $length);
return $bytes_written;
} | [
"protected",
"function",
"message_write",
"(",
"Base",
"$",
"object",
",",
"&",
"$",
"length",
"=",
"0",
")",
"{",
"Debug",
"::",
"Log",
"(",
"Debug",
"::",
"DEBUG",
",",
"'Message write: message_type='",
".",
"Message",
"::",
"$",
"name",
"[",
"$",
"obj... | Write Message Object
@param Message\Base $object
@param int & $length
@return int
@throws Exception | [
"Write",
"Message",
"Object"
] | 38cf01a177ed8e6ff387cdefcf11ba42594e330f | https://github.com/sskaje/mqtt/blob/38cf01a177ed8e6ff387cdefcf11ba42594e330f/mqtt/MQTT.php#L1221-L1228 | train |
glooby/task-bundle | src/DependencyInjection/Compiler/RegisterSchedulesPass.php | RegisterSchedulesPass.isTaskImplementation | private function isTaskImplementation($class)
{
if (!isset($this->implementations[$class])) {
$reflectionClass = new \ReflectionClass($class);
$this->implementations[$class] = $reflectionClass->implementsInterface(TaskInterface::class);
}
return $this->implementations[$class];
} | php | private function isTaskImplementation($class)
{
if (!isset($this->implementations[$class])) {
$reflectionClass = new \ReflectionClass($class);
$this->implementations[$class] = $reflectionClass->implementsInterface(TaskInterface::class);
}
return $this->implementations[$class];
} | [
"private",
"function",
"isTaskImplementation",
"(",
"$",
"class",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"implementations",
"[",
"$",
"class",
"]",
")",
")",
"{",
"$",
"reflectionClass",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
... | Returns whether the class implements TaskInterface.
@param string $class
@return bool | [
"Returns",
"whether",
"the",
"class",
"implements",
"TaskInterface",
"."
] | 3c97bc6a5e32f6d34bf86265a970ade707271f71 | https://github.com/glooby/task-bundle/blob/3c97bc6a5e32f6d34bf86265a970ade707271f71/src/DependencyInjection/Compiler/RegisterSchedulesPass.php#L42-L50 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTable.php | StatsTable.removeColumns | public function removeColumns(array $columns)
{
$columnsMap = array_flip($columns);
$this->removeColumnsInLine($this->headers, $columnsMap);
$this->removeColumnsInLine($this->aggregations, $columnsMap);
$this->removeColumnsInLine($this->dataFormats, $columnsMap);
$this->removeColumnsInLine($this->aggregationsFormats, $columnsMap);
foreach ($this->data as &$line) {
$this->removeColumnsInLine($line, $columnsMap);
}
return $this;
} | php | public function removeColumns(array $columns)
{
$columnsMap = array_flip($columns);
$this->removeColumnsInLine($this->headers, $columnsMap);
$this->removeColumnsInLine($this->aggregations, $columnsMap);
$this->removeColumnsInLine($this->dataFormats, $columnsMap);
$this->removeColumnsInLine($this->aggregationsFormats, $columnsMap);
foreach ($this->data as &$line) {
$this->removeColumnsInLine($line, $columnsMap);
}
return $this;
} | [
"public",
"function",
"removeColumns",
"(",
"array",
"$",
"columns",
")",
"{",
"$",
"columnsMap",
"=",
"array_flip",
"(",
"$",
"columns",
")",
";",
"$",
"this",
"->",
"removeColumnsInLine",
"(",
"$",
"this",
"->",
"headers",
",",
"$",
"columnsMap",
")",
... | Remove columns in table
@param array $columns
@return StatsTable | [
"Remove",
"columns",
"in",
"table"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTable.php#L108-L122 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTable.php | StatsTable.removeColumnsInLine | protected function removeColumnsInLine(array &$line, array $columnsMap)
{
foreach ($line as $k => $v) {
if (array_key_exists($k, $columnsMap)) {
unset($line[$k]);
}
}
} | php | protected function removeColumnsInLine(array &$line, array $columnsMap)
{
foreach ($line as $k => $v) {
if (array_key_exists($k, $columnsMap)) {
unset($line[$k]);
}
}
} | [
"protected",
"function",
"removeColumnsInLine",
"(",
"array",
"&",
"$",
"line",
",",
"array",
"$",
"columnsMap",
")",
"{",
"foreach",
"(",
"$",
"line",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"k",
",",
"$",
... | Internal helper to remove columns for a line.
@param array $line Line to filter. Referenced.
@param array $columnsMap An array indexed by columns to exclude. Value doesn't matter.
@return void | [
"Internal",
"helper",
"to",
"remove",
"columns",
"for",
"a",
"line",
"."
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTable.php#L132-L139 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTable.php | StatsTable.sortMultipleColumn | public function sortMultipleColumn($columns)
{
$compareFuncList = [];
foreach($columns as $colName=>$asc) {
$columnFormat = array_key_exists($colName, $this->dataFormats) ? $this->dataFormats[$colName] : Format::STRING;
$compareFuncList[$colName] = $this->_getFunctionForFormat($columnFormat, $asc);
}
$this->uSortMultipleColumn($compareFuncList);
return $this;
} | php | public function sortMultipleColumn($columns)
{
$compareFuncList = [];
foreach($columns as $colName=>$asc) {
$columnFormat = array_key_exists($colName, $this->dataFormats) ? $this->dataFormats[$colName] : Format::STRING;
$compareFuncList[$colName] = $this->_getFunctionForFormat($columnFormat, $asc);
}
$this->uSortMultipleColumn($compareFuncList);
return $this;
} | [
"public",
"function",
"sortMultipleColumn",
"(",
"$",
"columns",
")",
"{",
"$",
"compareFuncList",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"colName",
"=>",
"$",
"asc",
")",
"{",
"$",
"columnFormat",
"=",
"array_key_exists",
"(",
"$... | Sort stats table by multiple column
@param array $columns Associative array : KEY=> column name (string), VALUE=> Sort direction (boolean)
@return $this | [
"Sort",
"stats",
"table",
"by",
"multiple",
"column"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTable.php#L170-L180 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTable.php | StatsTable.uSortMultipleColumn | public function uSortMultipleColumn($columns)
{
$dataFormats = $this->dataFormats;
$sort = function ($a, $b) use ($columns, $dataFormats) {
foreach ($columns as $colName => $fn) {
$tmp = $fn($a[$colName], $b[$colName]);
if ($tmp !== 0) {
return $tmp;
}
}
return 0;
};
uasort($this->data, $sort);
return $this;
} | php | public function uSortMultipleColumn($columns)
{
$dataFormats = $this->dataFormats;
$sort = function ($a, $b) use ($columns, $dataFormats) {
foreach ($columns as $colName => $fn) {
$tmp = $fn($a[$colName], $b[$colName]);
if ($tmp !== 0) {
return $tmp;
}
}
return 0;
};
uasort($this->data, $sort);
return $this;
} | [
"public",
"function",
"uSortMultipleColumn",
"(",
"$",
"columns",
")",
"{",
"$",
"dataFormats",
"=",
"$",
"this",
"->",
"dataFormats",
";",
"$",
"sort",
"=",
"function",
"(",
"$",
"a",
",",
"$",
"b",
")",
"use",
"(",
"$",
"columns",
",",
"$",
"dataFo... | Sort stats table by multiple column with a custom compare function
@param $columns $columns Associative array : KEY=> column name (string), VALUE=> Custom function (function)
@return $this | [
"Sort",
"stats",
"table",
"by",
"multiple",
"column",
"with",
"a",
"custom",
"compare",
"function"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTable.php#L187-L202 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/Dumper/Excel/ExcelDumper.php | ExcelDumper.dump | public function dump(StatsTable $statsTable)
{
$excel = new Spreadsheet();
$excel->getDefaultStyle()->applyFromArray($this->getDefaultStyleArray());
$sheet = $excel->getActiveSheet();
$row = 1;
$data = $statsTable->getData();
$width = count(reset($data));
// HEADERS //
if ($this->enableHeaders) {
$headerStyle = new Style();
$headerStyle->applyFromArray($this->getHeadersStyleArray());
$col = 0;
foreach ($statsTable->getHeaders() as $header) {
$sheet->setCellValueByColumnAndRow($col, $row, $header);
$col++;
}
$sheet->duplicateStyle($headerStyle, 'A1:'. Coordinate::stringFromColumnIndex($width-1).'1');
$row++;
}
// DATA //
foreach ($statsTable->getData() as $data) {
$this->applyValues($sheet, $row, $data, $statsTable->getDataFormats());
$row++;
}
// AGGREGATIONS //
if ($this->enableAggregation) {
$this->applyValues($sheet, $row, $statsTable->getAggregations(), $statsTable->getAggregationsFormats(), $this->getAggregationsStyleArray());
}
// FINAL FORMATTING //
for ($col = 0; $col < $width; $col++) {
$sheet
->getColumnDimension(Coordinate::stringFromColumnIndex($col))
->setAutoSize(true);
}
$xlsDumper = new Xlsx($excel);
$pFilename = @tempnam(sys_get_temp_dir(), 'phpxltmp');
$xlsDumper->save($pFilename);
$contents = file_get_contents($pFilename);
@unlink($pFilename);
unset($excel);
unset($xlsDumper);
return $contents;
} | php | public function dump(StatsTable $statsTable)
{
$excel = new Spreadsheet();
$excel->getDefaultStyle()->applyFromArray($this->getDefaultStyleArray());
$sheet = $excel->getActiveSheet();
$row = 1;
$data = $statsTable->getData();
$width = count(reset($data));
// HEADERS //
if ($this->enableHeaders) {
$headerStyle = new Style();
$headerStyle->applyFromArray($this->getHeadersStyleArray());
$col = 0;
foreach ($statsTable->getHeaders() as $header) {
$sheet->setCellValueByColumnAndRow($col, $row, $header);
$col++;
}
$sheet->duplicateStyle($headerStyle, 'A1:'. Coordinate::stringFromColumnIndex($width-1).'1');
$row++;
}
// DATA //
foreach ($statsTable->getData() as $data) {
$this->applyValues($sheet, $row, $data, $statsTable->getDataFormats());
$row++;
}
// AGGREGATIONS //
if ($this->enableAggregation) {
$this->applyValues($sheet, $row, $statsTable->getAggregations(), $statsTable->getAggregationsFormats(), $this->getAggregationsStyleArray());
}
// FINAL FORMATTING //
for ($col = 0; $col < $width; $col++) {
$sheet
->getColumnDimension(Coordinate::stringFromColumnIndex($col))
->setAutoSize(true);
}
$xlsDumper = new Xlsx($excel);
$pFilename = @tempnam(sys_get_temp_dir(), 'phpxltmp');
$xlsDumper->save($pFilename);
$contents = file_get_contents($pFilename);
@unlink($pFilename);
unset($excel);
unset($xlsDumper);
return $contents;
} | [
"public",
"function",
"dump",
"(",
"StatsTable",
"$",
"statsTable",
")",
"{",
"$",
"excel",
"=",
"new",
"Spreadsheet",
"(",
")",
";",
"$",
"excel",
"->",
"getDefaultStyle",
"(",
")",
"->",
"applyFromArray",
"(",
"$",
"this",
"->",
"getDefaultStyleArray",
"... | Dumps the stats table
@param StatsTable $statsTable
@return string
@throws \Exception | [
"Dumps",
"the",
"stats",
"table"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/Dumper/Excel/ExcelDumper.php#L64-L118 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/Dumper/Excel/ExcelDumper.php | ExcelDumper.getDefaultStyleArrayForRow | protected function getDefaultStyleArrayForRow($row)
{
$style = $this->getDefaultStyleForFilledCells();
if ($this->getOption(self::OPTION_ZEBRA)) {
if (($row % 2) == 0) {
$bgColor = $this->getOption(self::OPTION_ZEBRA_COLOR_EVEN);
} else {
$bgColor = $this->getOption(self::OPTION_ZEBRA_COLOR_ODD);
}
if ($bgColor) {
$style['fill'] = [
'fillType' => Fill::FILL_SOLID,
'color' => ['argb' => $bgColor],
];
}
}
return $style;
} | php | protected function getDefaultStyleArrayForRow($row)
{
$style = $this->getDefaultStyleForFilledCells();
if ($this->getOption(self::OPTION_ZEBRA)) {
if (($row % 2) == 0) {
$bgColor = $this->getOption(self::OPTION_ZEBRA_COLOR_EVEN);
} else {
$bgColor = $this->getOption(self::OPTION_ZEBRA_COLOR_ODD);
}
if ($bgColor) {
$style['fill'] = [
'fillType' => Fill::FILL_SOLID,
'color' => ['argb' => $bgColor],
];
}
}
return $style;
} | [
"protected",
"function",
"getDefaultStyleArrayForRow",
"(",
"$",
"row",
")",
"{",
"$",
"style",
"=",
"$",
"this",
"->",
"getDefaultStyleForFilledCells",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"getOption",
"(",
"self",
"::",
"OPTION_ZEBRA",
")",
")",
... | Get default style for a given row
@param integer $row
@return array | [
"Get",
"default",
"style",
"for",
"a",
"given",
"row"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/Dumper/Excel/ExcelDumper.php#L155-L175 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/Dumper/Excel/ExcelDumper.php | ExcelDumper.getOption | public function getOption($optionName)
{
if (array_key_exists($optionName, $this->options)) {
return $this->options[$optionName];
} else {
return null;
}
} | php | public function getOption($optionName)
{
if (array_key_exists($optionName, $this->options)) {
return $this->options[$optionName];
} else {
return null;
}
} | [
"public",
"function",
"getOption",
"(",
"$",
"optionName",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"optionName",
",",
"$",
"this",
"->",
"options",
")",
")",
"{",
"return",
"$",
"this",
"->",
"options",
"[",
"$",
"optionName",
"]",
";",
"}",... | Gets an option
@param $optionName
@return null | [
"Gets",
"an",
"option"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/Dumper/Excel/ExcelDumper.php#L230-L237 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/Dumper/Excel/ExcelDumper.php | ExcelDumper.applyValues | protected function applyValues(Worksheet $sheet, $row, $values, $formats, $styleArray = [])
{
$col = 0;
foreach ($values as $index => $value) {
$this->applyValue($sheet, $col, $row, $value, array_key_exists($index, $formats) ? $formats[$index] : Format::STRING, $styleArray);
$col++;
}
} | php | protected function applyValues(Worksheet $sheet, $row, $values, $formats, $styleArray = [])
{
$col = 0;
foreach ($values as $index => $value) {
$this->applyValue($sheet, $col, $row, $value, array_key_exists($index, $formats) ? $formats[$index] : Format::STRING, $styleArray);
$col++;
}
} | [
"protected",
"function",
"applyValues",
"(",
"Worksheet",
"$",
"sheet",
",",
"$",
"row",
",",
"$",
"values",
",",
"$",
"formats",
",",
"$",
"styleArray",
"=",
"[",
"]",
")",
"{",
"$",
"col",
"=",
"0",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
... | Set values in specific row
@param Worksheet $sheet The worksheet
@param integer $row The selected row
@param array $values The values to insert
@param array $formats Associative arrays with formats
@param array $styleArray An array representing the style
@throws \Exception | [
"Set",
"values",
"in",
"specific",
"row"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/Dumper/Excel/ExcelDumper.php#L248-L255 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/Dumper/Excel/ExcelDumper.php | ExcelDumper.applyValue | protected function applyValue(Worksheet $sheet, $col, $row, $value, $format, $styleArray = [])
{
if (0 == count($styleArray)) {
$styleArray = $this->getDefaultStyleArrayForRow($row);
}
$style = new Style();
$style->applyFromArray($styleArray);
switch ($format) {
case Format::DATE:
if (!($value instanceof \DateTime)) {
$date = new \DateTime($value);
} else {
$date = $value;
}
$value = Date::PHPToExcel($date);
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_YYYYMMDD2);
break;
case Format::DATETIME:
if (!($value instanceof \DateTime)) {
$date = new \DateTime($value);
} else {
$date = $value;
}
$value = Date::PHPToExcel($date);
$style->getNumberFormat()->setFormatCode(self::FORMAT_DATETIME);
break;
case Format::FLOAT2:
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
break;
case Format::INTEGER:
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_NUMBER);
break;
case Format::MONEY:
case Format::MONEY2:
$style->getNumberFormat()->setFormatCode(self::FORMAT_EUR);
break;
case Format::PCT:
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE);
break;
case Format::PCT2:
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE_00);
break;
case Format::STRING:
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
break;
}
$sheet->setCellValueByColumnAndRow($col, $row, $value);
$sheet->duplicateStyle($style, Coordinate::stringFromColumnIndex($col).$row);
} | php | protected function applyValue(Worksheet $sheet, $col, $row, $value, $format, $styleArray = [])
{
if (0 == count($styleArray)) {
$styleArray = $this->getDefaultStyleArrayForRow($row);
}
$style = new Style();
$style->applyFromArray($styleArray);
switch ($format) {
case Format::DATE:
if (!($value instanceof \DateTime)) {
$date = new \DateTime($value);
} else {
$date = $value;
}
$value = Date::PHPToExcel($date);
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_YYYYMMDD2);
break;
case Format::DATETIME:
if (!($value instanceof \DateTime)) {
$date = new \DateTime($value);
} else {
$date = $value;
}
$value = Date::PHPToExcel($date);
$style->getNumberFormat()->setFormatCode(self::FORMAT_DATETIME);
break;
case Format::FLOAT2:
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
break;
case Format::INTEGER:
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_NUMBER);
break;
case Format::MONEY:
case Format::MONEY2:
$style->getNumberFormat()->setFormatCode(self::FORMAT_EUR);
break;
case Format::PCT:
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE);
break;
case Format::PCT2:
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE_00);
break;
case Format::STRING:
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
break;
}
$sheet->setCellValueByColumnAndRow($col, $row, $value);
$sheet->duplicateStyle($style, Coordinate::stringFromColumnIndex($col).$row);
} | [
"protected",
"function",
"applyValue",
"(",
"Worksheet",
"$",
"sheet",
",",
"$",
"col",
",",
"$",
"row",
",",
"$",
"value",
",",
"$",
"format",
",",
"$",
"styleArray",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"0",
"==",
"count",
"(",
"$",
"styleArray",
... | Set value in specific cell
@param Worksheet $sheet The worksheet
@param integer $col The selected column
@param integer $row The selected row
@param array $value The values to insert
@param array $format Associative arrays with formats
@param array $styleArray An array representing the style
@throws \Exception | [
"Set",
"value",
"in",
"specific",
"cell"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/Dumper/Excel/ExcelDumper.php#L267-L325 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTableBuilder.php | StatsTableBuilder.addIndexesAsColumn | public function addIndexesAsColumn($columnName, $headerName = null, $format = null, AggregationInterface $aggregation = null, $metaData = [])
{
$values = [];
foreach ($this->indexes as $index) {
$values[$index] = $index;
}
$column = new StatsColumnBuilder(
$values,
$headerName,
$format,
$aggregation,
$metaData
);
$columns = array_reverse($this->columns);
$columns[$columnName] = $column;
$this->columns = $columns;
} | php | public function addIndexesAsColumn($columnName, $headerName = null, $format = null, AggregationInterface $aggregation = null, $metaData = [])
{
$values = [];
foreach ($this->indexes as $index) {
$values[$index] = $index;
}
$column = new StatsColumnBuilder(
$values,
$headerName,
$format,
$aggregation,
$metaData
);
$columns = array_reverse($this->columns);
$columns[$columnName] = $column;
$this->columns = $columns;
} | [
"public",
"function",
"addIndexesAsColumn",
"(",
"$",
"columnName",
",",
"$",
"headerName",
"=",
"null",
",",
"$",
"format",
"=",
"null",
",",
"AggregationInterface",
"$",
"aggregation",
"=",
"null",
",",
"$",
"metaData",
"=",
"[",
"]",
")",
"{",
"$",
"v... | Add index of data as a new column
@param $columnName
@param null $headerName
@param null $format
@param AggregationInterface $aggregation | [
"Add",
"index",
"of",
"data",
"as",
"a",
"new",
"column"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTableBuilder.php#L62-L80 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTableBuilder.php | StatsTableBuilder.appendTable | public function appendTable(
$table,
$headers,
$formats,
$aggregations,
$columnNames = [],
$defaultValues = [],
$metaData = []
) {
$this->defaultValues = array_merge($this->defaultValues, $defaultValues);
if (count($columnNames) === 0 && count($table) !== 0) {
$columnNames = array_keys(reset($table));
}
if (count($columnNames) === 0 && count($headers) !== 0) {
$columnNames = array_keys($headers);
}
foreach ($columnNames as $columnName) {
$column = new StatsColumnBuilder(
$this->getAssocColumn($table, $columnName),
$this->getParameter($headers, $columnName, $columnName),
$this->getParameter($formats, $columnName),
$this->getParameter($aggregations, $columnName),
$this->getParameter($metaData, $columnName, [])
);
if (count($this->defaultValues)) {
$column->insureIsFilled($this->indexes, $this->defaultValues[$columnName]);
}
$this->columns[$columnName] = $column;
}
} | php | public function appendTable(
$table,
$headers,
$formats,
$aggregations,
$columnNames = [],
$defaultValues = [],
$metaData = []
) {
$this->defaultValues = array_merge($this->defaultValues, $defaultValues);
if (count($columnNames) === 0 && count($table) !== 0) {
$columnNames = array_keys(reset($table));
}
if (count($columnNames) === 0 && count($headers) !== 0) {
$columnNames = array_keys($headers);
}
foreach ($columnNames as $columnName) {
$column = new StatsColumnBuilder(
$this->getAssocColumn($table, $columnName),
$this->getParameter($headers, $columnName, $columnName),
$this->getParameter($formats, $columnName),
$this->getParameter($aggregations, $columnName),
$this->getParameter($metaData, $columnName, [])
);
if (count($this->defaultValues)) {
$column->insureIsFilled($this->indexes, $this->defaultValues[$columnName]);
}
$this->columns[$columnName] = $column;
}
} | [
"public",
"function",
"appendTable",
"(",
"$",
"table",
",",
"$",
"headers",
",",
"$",
"formats",
",",
"$",
"aggregations",
",",
"$",
"columnNames",
"=",
"[",
"]",
",",
"$",
"defaultValues",
"=",
"[",
"]",
",",
"$",
"metaData",
"=",
"[",
"]",
")",
... | Append columns given a table
@param array $table
@param string[] $headers
@param string[] $formats
@param AggregationInterface[] $aggregations
@param string[] $columnNames
@param mixed[] $defaultValues | [
"Append",
"columns",
"given",
"a",
"table"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTableBuilder.php#L92-L126 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTableBuilder.php | StatsTableBuilder.getParameter | private function getParameter($values, $key, $defaultValue = null)
{
return array_key_exists($key, $values) ? $values[$key] : $defaultValue;
} | php | private function getParameter($values, $key, $defaultValue = null)
{
return array_key_exists($key, $values) ? $values[$key] : $defaultValue;
} | [
"private",
"function",
"getParameter",
"(",
"$",
"values",
",",
"$",
"key",
",",
"$",
"defaultValue",
"=",
"null",
")",
"{",
"return",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"values",
")",
"?",
"$",
"values",
"[",
"$",
"key",
"]",
":",
"$",
... | Get an indexed value in a table. Same as ParameterBag
@param array $values
@param mixed $key
@param mixed $defaultValue
@return mixed | [
"Get",
"an",
"indexed",
"value",
"in",
"a",
"table",
".",
"Same",
"as",
"ParameterBag"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTableBuilder.php#L135-L138 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTableBuilder.php | StatsTableBuilder.getAssocColumn | public function getAssocColumn($table, $columnName, $defaultValue = null)
{
$values = [];
foreach ($table as $key => $line) {
if (array_key_exists($columnName, $line)) {
$values[$key] = $line[$columnName];
} else {
$values[$key] = $defaultValue;
}
}
return $values;
} | php | public function getAssocColumn($table, $columnName, $defaultValue = null)
{
$values = [];
foreach ($table as $key => $line) {
if (array_key_exists($columnName, $line)) {
$values[$key] = $line[$columnName];
} else {
$values[$key] = $defaultValue;
}
}
return $values;
} | [
"public",
"function",
"getAssocColumn",
"(",
"$",
"table",
",",
"$",
"columnName",
",",
"$",
"defaultValue",
"=",
"null",
")",
"{",
"$",
"values",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"table",
"as",
"$",
"key",
"=>",
"$",
"line",
")",
"{",
"if"... | Returns an associative table only with selected column.
Fill with default value if column not in a row
@param array $table
@param string $columnName
@param mixed $defaultValue
@return array The column | [
"Returns",
"an",
"associative",
"table",
"only",
"with",
"selected",
"column",
".",
"Fill",
"with",
"default",
"value",
"if",
"column",
"not",
"in",
"a",
"row"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTableBuilder.php#L148-L160 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTableBuilder.php | StatsTableBuilder.getColumn | public function getColumn($columnName)
{
if (!array_key_exists($columnName, $this->columns)) {
throw new \InvalidArgumentException('Unable to find column '.$columnName.' in columns '.join(',', array_keys($this->columns)));
}
return $this->columns[$columnName];
} | php | public function getColumn($columnName)
{
if (!array_key_exists($columnName, $this->columns)) {
throw new \InvalidArgumentException('Unable to find column '.$columnName.' in columns '.join(',', array_keys($this->columns)));
}
return $this->columns[$columnName];
} | [
"public",
"function",
"getColumn",
"(",
"$",
"columnName",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"columnName",
",",
"$",
"this",
"->",
"columns",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Unable to find column '"... | Retrieve a column
@return StatsColumnBuilder
@throws \InvalidArgumentException | [
"Retrieve",
"a",
"column"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTableBuilder.php#L167-L174 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTableBuilder.php | StatsTableBuilder.addDynamicColumn | public function addDynamicColumn($columnName, DynamicColumnBuilderInterface $dynamicColumn, $header = '', $format = null, AggregationInterface $aggregation = null, $metaData = [])
{
$values = $dynamicColumn->buildColumnValues($this);
$this->columns[$columnName] = new StatsColumnBuilder($values, $header, $format, $aggregation, $metaData);
} | php | public function addDynamicColumn($columnName, DynamicColumnBuilderInterface $dynamicColumn, $header = '', $format = null, AggregationInterface $aggregation = null, $metaData = [])
{
$values = $dynamicColumn->buildColumnValues($this);
$this->columns[$columnName] = new StatsColumnBuilder($values, $header, $format, $aggregation, $metaData);
} | [
"public",
"function",
"addDynamicColumn",
"(",
"$",
"columnName",
",",
"DynamicColumnBuilderInterface",
"$",
"dynamicColumn",
",",
"$",
"header",
"=",
"''",
",",
"$",
"format",
"=",
"null",
",",
"AggregationInterface",
"$",
"aggregation",
"=",
"null",
",",
"$",
... | Add a dynamic column
@param mixed $columnName
@param DynamicColumnBuilderInterface $dynamicColumn
@param string $header
@param string $format
@param AggregationInterface $aggregation | [
"Add",
"a",
"dynamic",
"column"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTableBuilder.php#L194-L198 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTableBuilder.php | StatsTableBuilder.build | public function build($columns = [])
{
$headers = [];
$data = [];
$dataFormats = [];
$aggregations = [];
$aggregationsFormats = [];
$metaData = [];
foreach ($this->indexes as $index) {
$columnsNames = array_keys($this->columns);
$line = [];
foreach ($columnsNames as $columnName) {
$columnValues = $this->columns[$columnName]->getValues();
$line = array_merge($line, [$columnName => $columnValues[$index]]);
}
$data[$index] = $this->orderColumns($line, $columns);
}
foreach ($this->columns as $columnName => $column) {
$dataFormats[$columnName] = $column->getFormat();
$headers = array_merge($headers, [$columnName => $column->getHeaderName()]);
$metaData = array_merge($metaData, [$columnName => $column->getMetaData()]);
$columnAggregation = $column->getAggregation();
if ($columnAggregation) {
$aggregationValue = $columnAggregation->aggregate($this);
$aggregationsFormats[$columnName] = $columnAggregation->getFormat();
} else {
$aggregationValue = null;
}
$aggregations = array_merge($aggregations, [$columnName => $aggregationValue]);
}
$headers = $this->orderColumns($headers, $columns);
$metaData = $this->orderColumns($metaData, $columns);
$aggregations = $this->orderColumns($aggregations, $columns);
return new StatsTable($data, $headers, $aggregations, $dataFormats, $aggregationsFormats, $metaData);
} | php | public function build($columns = [])
{
$headers = [];
$data = [];
$dataFormats = [];
$aggregations = [];
$aggregationsFormats = [];
$metaData = [];
foreach ($this->indexes as $index) {
$columnsNames = array_keys($this->columns);
$line = [];
foreach ($columnsNames as $columnName) {
$columnValues = $this->columns[$columnName]->getValues();
$line = array_merge($line, [$columnName => $columnValues[$index]]);
}
$data[$index] = $this->orderColumns($line, $columns);
}
foreach ($this->columns as $columnName => $column) {
$dataFormats[$columnName] = $column->getFormat();
$headers = array_merge($headers, [$columnName => $column->getHeaderName()]);
$metaData = array_merge($metaData, [$columnName => $column->getMetaData()]);
$columnAggregation = $column->getAggregation();
if ($columnAggregation) {
$aggregationValue = $columnAggregation->aggregate($this);
$aggregationsFormats[$columnName] = $columnAggregation->getFormat();
} else {
$aggregationValue = null;
}
$aggregations = array_merge($aggregations, [$columnName => $aggregationValue]);
}
$headers = $this->orderColumns($headers, $columns);
$metaData = $this->orderColumns($metaData, $columns);
$aggregations = $this->orderColumns($aggregations, $columns);
return new StatsTable($data, $headers, $aggregations, $dataFormats, $aggregationsFormats, $metaData);
} | [
"public",
"function",
"build",
"(",
"$",
"columns",
"=",
"[",
"]",
")",
"{",
"$",
"headers",
"=",
"[",
"]",
";",
"$",
"data",
"=",
"[",
"]",
";",
"$",
"dataFormats",
"=",
"[",
"]",
";",
"$",
"aggregations",
"=",
"[",
"]",
";",
"$",
"aggregation... | Build the data
@param array $columns Desired columns
@return StatsTable | [
"Build",
"the",
"data"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTableBuilder.php#L218-L261 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTableBuilder.php | StatsTableBuilder.orderColumns | public static function orderColumns($table, $columns)
{
// If no columns given, return table as-is
if (!$columns) {
return $table;
}
// Order
$result = [];
foreach ($columns as $column) {
if (array_key_exists($column, $table)) {
$result[$column] = $table[$column];
}
}
return $result;
} | php | public static function orderColumns($table, $columns)
{
// If no columns given, return table as-is
if (!$columns) {
return $table;
}
// Order
$result = [];
foreach ($columns as $column) {
if (array_key_exists($column, $table)) {
$result[$column] = $table[$column];
}
}
return $result;
} | [
"public",
"static",
"function",
"orderColumns",
"(",
"$",
"table",
",",
"$",
"columns",
")",
"{",
"// If no columns given, return table as-is",
"if",
"(",
"!",
"$",
"columns",
")",
"{",
"return",
"$",
"table",
";",
"}",
"// Order",
"$",
"result",
"=",
"[",
... | Order table columns given columns table
@param array $table
@param array $columns
@return array | [
"Order",
"table",
"columns",
"given",
"columns",
"table"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTableBuilder.php#L269-L285 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsTableBuilder.php | StatsTableBuilder.groupBy | public function groupBy($columns, array $excludeColumns = [])
{
$groupedData = [];
$statsTable = $this->build();
foreach ($statsTable->getData() as $line) {
$key = join(
'-_##_-',
array_map(
function ($c) use ($line) {
return $line[$c];
},
$columns
)
);
$groupedData[$key][] = $line;
}
$filterLine = function ($line) use ($excludeColumns) {
foreach ($excludeColumns as $c) {
unset($line[$c]);
}
return $line;
};
$headers = $filterLine(
array_map(
function (StatsColumnBuilder $c) {
return $c->getHeaderName();
},
$this->columns
)
);
$formats = $filterLine(
array_map(
function (StatsColumnBuilder $c) {
return $c->getFormat();
},
$this->columns
)
);
$aggregations = $filterLine(
array_map(
function (StatsColumnBuilder $c) {
return $c->getAggregation();
},
$this->columns
)
);
$metaData = $filterLine(
array_map(
function (StatsColumnBuilder $c) {
return $c->getMetaData();
},
$this->columns
)
);
$data = [];
foreach ($groupedData as $lines) {
$tmpAggregations = $aggregations;
// Add static aggragation for group by fields
foreach ($columns as $column) {
$oneLine = current($lines);
$value = $oneLine[$column];
$tmpAggregations[$column] = new StaticAggregation($value, Format::STRING);
}
$tmpTableBuilder = new StatsTableBuilder(
array_map($filterLine, $lines),
$headers,
$formats,
$tmpAggregations,
[],
[],
null,
$metaData
);
$tmpTable = $tmpTableBuilder->build();
$data[] = $tmpTable->getAggregations();
}
return new StatsTableBuilder(
$data,
$headers,
$formats,
$aggregations,
[],
[],
null,
$metaData
);
} | php | public function groupBy($columns, array $excludeColumns = [])
{
$groupedData = [];
$statsTable = $this->build();
foreach ($statsTable->getData() as $line) {
$key = join(
'-_##_-',
array_map(
function ($c) use ($line) {
return $line[$c];
},
$columns
)
);
$groupedData[$key][] = $line;
}
$filterLine = function ($line) use ($excludeColumns) {
foreach ($excludeColumns as $c) {
unset($line[$c]);
}
return $line;
};
$headers = $filterLine(
array_map(
function (StatsColumnBuilder $c) {
return $c->getHeaderName();
},
$this->columns
)
);
$formats = $filterLine(
array_map(
function (StatsColumnBuilder $c) {
return $c->getFormat();
},
$this->columns
)
);
$aggregations = $filterLine(
array_map(
function (StatsColumnBuilder $c) {
return $c->getAggregation();
},
$this->columns
)
);
$metaData = $filterLine(
array_map(
function (StatsColumnBuilder $c) {
return $c->getMetaData();
},
$this->columns
)
);
$data = [];
foreach ($groupedData as $lines) {
$tmpAggregations = $aggregations;
// Add static aggragation for group by fields
foreach ($columns as $column) {
$oneLine = current($lines);
$value = $oneLine[$column];
$tmpAggregations[$column] = new StaticAggregation($value, Format::STRING);
}
$tmpTableBuilder = new StatsTableBuilder(
array_map($filterLine, $lines),
$headers,
$formats,
$tmpAggregations,
[],
[],
null,
$metaData
);
$tmpTable = $tmpTableBuilder->build();
$data[] = $tmpTable->getAggregations();
}
return new StatsTableBuilder(
$data,
$headers,
$formats,
$aggregations,
[],
[],
null,
$metaData
);
} | [
"public",
"function",
"groupBy",
"(",
"$",
"columns",
",",
"array",
"$",
"excludeColumns",
"=",
"[",
"]",
")",
"{",
"$",
"groupedData",
"=",
"[",
"]",
";",
"$",
"statsTable",
"=",
"$",
"this",
"->",
"build",
"(",
")",
";",
"foreach",
"(",
"$",
"sta... | Do a groupBy on columns, using aggregations to aggregate data per line
@param string|array $columns Columns to aggregate
@param array $excludeColumns Irrelevant columns to exclude
@return StatsTableBuilder | [
"Do",
"a",
"groupBy",
"on",
"columns",
"using",
"aggregations",
"to",
"aggregate",
"data",
"per",
"line"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsTableBuilder.php#L303-L398 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/Dumper/JSON/JSONDumper.php | JSONDumper.formatValue | protected function formatValue($format, $value)
{
switch ($format) {
case Format::DATE:
case Format::DATETIME:
if ($value instanceof \DateTime) {
return $value->format('c');
}
break;
case Format::FLOAT2:
case Format::MONEY2:
return floatval(sprintf("%.2f", $value));
case Format::PCT2:
return floatval(sprintf('%.2f', $value*100));
case Format::PCT:
return intval(sprintf('%d', $value*100));
case Format::INTEGER:
case Format::MONEY:
return intval(sprintf("%d", $value));
}
return $value;
} | php | protected function formatValue($format, $value)
{
switch ($format) {
case Format::DATE:
case Format::DATETIME:
if ($value instanceof \DateTime) {
return $value->format('c');
}
break;
case Format::FLOAT2:
case Format::MONEY2:
return floatval(sprintf("%.2f", $value));
case Format::PCT2:
return floatval(sprintf('%.2f', $value*100));
case Format::PCT:
return intval(sprintf('%d', $value*100));
case Format::INTEGER:
case Format::MONEY:
return intval(sprintf("%d", $value));
}
return $value;
} | [
"protected",
"function",
"formatValue",
"(",
"$",
"format",
",",
"$",
"value",
")",
"{",
"switch",
"(",
"$",
"format",
")",
"{",
"case",
"Format",
"::",
"DATE",
":",
"case",
"Format",
"::",
"DATETIME",
":",
"if",
"(",
"$",
"value",
"instanceof",
"\\",
... | Format values for JSON
@param $format
@param $value
@return float|int|string | [
"Format",
"values",
"for",
"JSON"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/Dumper/JSON/JSONDumper.php#L58-L84 | train |
igraal/stats-table | lib/IgraalOSL/StatsTable/StatsColumnBuilder.php | StatsColumnBuilder.insureIsFilled | public function insureIsFilled($indexes, $defaultValue)
{
$newValues = [];
foreach ($indexes as $index) {
$newValues[$index] = array_key_exists($index, $this->values) ? $this->values[$index] : $defaultValue;
}
$this->values = $newValues;
} | php | public function insureIsFilled($indexes, $defaultValue)
{
$newValues = [];
foreach ($indexes as $index) {
$newValues[$index] = array_key_exists($index, $this->values) ? $this->values[$index] : $defaultValue;
}
$this->values = $newValues;
} | [
"public",
"function",
"insureIsFilled",
"(",
"$",
"indexes",
",",
"$",
"defaultValue",
")",
"{",
"$",
"newValues",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"indexes",
"as",
"$",
"index",
")",
"{",
"$",
"newValues",
"[",
"$",
"index",
"]",
"=",
"array... | Ensure column is filled with given indexes. If not, it will be filled with default values
@param $indexes
@param $defaultValue | [
"Ensure",
"column",
"is",
"filled",
"with",
"given",
"indexes",
".",
"If",
"not",
"it",
"will",
"be",
"filled",
"with",
"default",
"values"
] | b3649f9a929567d0c585187f50331d61bcb3453f | https://github.com/igraal/stats-table/blob/b3649f9a929567d0c585187f50331d61bcb3453f/lib/IgraalOSL/StatsTable/StatsColumnBuilder.php#L112-L119 | train |
DevMarketer/LaravelEasyNav | src/DevMarketer/EasyNav/EasyNav.php | EasyNav.hasSegment | public function hasSegment($slugs, $segments = 1, $active = NULL)
{
$this->setActive($active);
$segments = (!is_array($segments) ? [$segments] : $segments);
$slugs = (!is_array($slugs) ? [$slugs] : $slugs);
foreach ($slugs as $slug) {
foreach ($segments as $segment) {
if ($this->request->segment($segment) == $slug) return $this->active;
}
}
return '';
} | php | public function hasSegment($slugs, $segments = 1, $active = NULL)
{
$this->setActive($active);
$segments = (!is_array($segments) ? [$segments] : $segments);
$slugs = (!is_array($slugs) ? [$slugs] : $slugs);
foreach ($slugs as $slug) {
foreach ($segments as $segment) {
if ($this->request->segment($segment) == $slug) return $this->active;
}
}
return '';
} | [
"public",
"function",
"hasSegment",
"(",
"$",
"slugs",
",",
"$",
"segments",
"=",
"1",
",",
"$",
"active",
"=",
"NULL",
")",
"{",
"$",
"this",
"->",
"setActive",
"(",
"$",
"active",
")",
";",
"$",
"segments",
"=",
"(",
"!",
"is_array",
"(",
"$",
... | returns the active class if the defined segment exists
in the current request URI
@param string|array $slugs
@param int|array $segments
@param string|NULL $active
@return string | [
"returns",
"the",
"active",
"class",
"if",
"the",
"defined",
"segment",
"exists",
"in",
"the",
"current",
"request",
"URI"
] | 517a7d5a35f443574c0ce883d458849cae7b3330 | https://github.com/DevMarketer/LaravelEasyNav/blob/517a7d5a35f443574c0ce883d458849cae7b3330/src/DevMarketer/EasyNav/EasyNav.php#L56-L67 | train |
DevMarketer/LaravelEasyNav | src/DevMarketer/EasyNav/EasyNav.php | EasyNav.isRoute | public function isRoute($route, $active = NULL)
{
$this->setActive($active);
return ($this->request->routeIs($route) ? $this->active : '');
} | php | public function isRoute($route, $active = NULL)
{
$this->setActive($active);
return ($this->request->routeIs($route) ? $this->active : '');
} | [
"public",
"function",
"isRoute",
"(",
"$",
"route",
",",
"$",
"active",
"=",
"NULL",
")",
"{",
"$",
"this",
"->",
"setActive",
"(",
"$",
"active",
")",
";",
"return",
"(",
"$",
"this",
"->",
"request",
"->",
"routeIs",
"(",
"$",
"route",
")",
"?",
... | Receives a named route and returns true or false depending
if the current URL is equal to the named route provided.
@param string $route
@param string|NULL $active
@return string | [
"Receives",
"a",
"named",
"route",
"and",
"returns",
"true",
"or",
"false",
"depending",
"if",
"the",
"current",
"URL",
"is",
"equal",
"to",
"the",
"named",
"route",
"provided",
"."
] | 517a7d5a35f443574c0ce883d458849cae7b3330 | https://github.com/DevMarketer/LaravelEasyNav/blob/517a7d5a35f443574c0ce883d458849cae7b3330/src/DevMarketer/EasyNav/EasyNav.php#L90-L94 | train |
DevMarketer/LaravelEasyNav | src/DevMarketer/EasyNav/EasyNav.php | EasyNav.isResource | public function isResource($resource, $prefix = NULL, $active = NULL, $strict = false)
{
$this->setActive($active);
if ($prefix && is_string($prefix)) {
$prefix = str_replace('.', '/', $prefix);
$search = trim($prefix,'/').'/'.trim($resource, '/');
} else {
$search = trim($resource, '/');
}
return ($this->pathContains($search, $strict) ? $this->active : '');
} | php | public function isResource($resource, $prefix = NULL, $active = NULL, $strict = false)
{
$this->setActive($active);
if ($prefix && is_string($prefix)) {
$prefix = str_replace('.', '/', $prefix);
$search = trim($prefix,'/').'/'.trim($resource, '/');
} else {
$search = trim($resource, '/');
}
return ($this->pathContains($search, $strict) ? $this->active : '');
} | [
"public",
"function",
"isResource",
"(",
"$",
"resource",
",",
"$",
"prefix",
"=",
"NULL",
",",
"$",
"active",
"=",
"NULL",
",",
"$",
"strict",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"setActive",
"(",
"$",
"active",
")",
";",
"if",
"(",
"$",
... | Checks if current page is one of a specified resouce
provided in the function. Also accepts a prefix or strict
mode to optionally prevent false-positives
@param string $resource
@param string|NULL $prefix
@param string $active
@param bool $strict
@return string | [
"Checks",
"if",
"current",
"page",
"is",
"one",
"of",
"a",
"specified",
"resouce",
"provided",
"in",
"the",
"function",
".",
"Also",
"accepts",
"a",
"prefix",
"or",
"strict",
"mode",
"to",
"optionally",
"prevent",
"false",
"-",
"positives"
] | 517a7d5a35f443574c0ce883d458849cae7b3330 | https://github.com/DevMarketer/LaravelEasyNav/blob/517a7d5a35f443574c0ce883d458849cae7b3330/src/DevMarketer/EasyNav/EasyNav.php#L107-L117 | train |
RNCryptor/RNCryptor-php | src/RNCryptor/Encryptor.php | Encryptor.encrypt | public function encrypt($plaintext, $password, $version = Cryptor::DEFAULT_SCHEMA_VERSION, $base64Encode = true)
{
$this->configure($version);
$components = $this->makeComponents($version);
$components->headers->encSalt = $this->makeSalt();
$components->headers->hmacSalt = $this->makeSalt();
$components->headers->iv = $this->makeIv($this->config->ivLength);
$encKey = $this->makeKey($components->headers->encSalt, $password);
$hmacKey = $this->makeKey($components->headers->hmacSalt, $password);
return $this->encryptFromComponents($plaintext, $components, $encKey, $hmacKey, $base64Encode);
} | php | public function encrypt($plaintext, $password, $version = Cryptor::DEFAULT_SCHEMA_VERSION, $base64Encode = true)
{
$this->configure($version);
$components = $this->makeComponents($version);
$components->headers->encSalt = $this->makeSalt();
$components->headers->hmacSalt = $this->makeSalt();
$components->headers->iv = $this->makeIv($this->config->ivLength);
$encKey = $this->makeKey($components->headers->encSalt, $password);
$hmacKey = $this->makeKey($components->headers->hmacSalt, $password);
return $this->encryptFromComponents($plaintext, $components, $encKey, $hmacKey, $base64Encode);
} | [
"public",
"function",
"encrypt",
"(",
"$",
"plaintext",
",",
"$",
"password",
",",
"$",
"version",
"=",
"Cryptor",
"::",
"DEFAULT_SCHEMA_VERSION",
",",
"$",
"base64Encode",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"configure",
"(",
"$",
"version",
")",
... | Encrypt plaintext using RNCryptor's algorithm
@param string $plaintext Text to be encrypted
@param string $password Password to use
@param int $version (Optional) RNCryptor schema version to use.
@throws \Exception If the provided version (if any) is unsupported
@return string Encrypted, Base64-encoded string | [
"Encrypt",
"plaintext",
"using",
"RNCryptor",
"s",
"algorithm"
] | bf07c357461994b223bb4e3433cf442902f6e68b | https://github.com/RNCryptor/RNCryptor-php/blob/bf07c357461994b223bb4e3433cf442902f6e68b/src/RNCryptor/Encryptor.php#L23-L36 | train |
RNCryptor/RNCryptor-php | src/RNCryptor/Decryptor.php | Decryptor.decrypt | public function decrypt($encryptedBase64Data, $password)
{
$components = $this->unpackEncryptedBase64Data($encryptedBase64Data);
if (!$this->hmacIsValid($components, $password)) {
return false;
}
$key = $this->makeKey($components->headers->encSalt, $password);
if ($this->config->mode == 'ctr') {
return $this->aesCtrLittleEndianCrypt($components->ciphertext, $key, $components->headers->iv);
}
$iv = (string)$components->headers->iv;
$method = $this->config->algorithm . 'cbc';
return openssl_decrypt($components->ciphertext, $method, $key, OPENSSL_RAW_DATA, (string)$iv);
} | php | public function decrypt($encryptedBase64Data, $password)
{
$components = $this->unpackEncryptedBase64Data($encryptedBase64Data);
if (!$this->hmacIsValid($components, $password)) {
return false;
}
$key = $this->makeKey($components->headers->encSalt, $password);
if ($this->config->mode == 'ctr') {
return $this->aesCtrLittleEndianCrypt($components->ciphertext, $key, $components->headers->iv);
}
$iv = (string)$components->headers->iv;
$method = $this->config->algorithm . 'cbc';
return openssl_decrypt($components->ciphertext, $method, $key, OPENSSL_RAW_DATA, (string)$iv);
} | [
"public",
"function",
"decrypt",
"(",
"$",
"encryptedBase64Data",
",",
"$",
"password",
")",
"{",
"$",
"components",
"=",
"$",
"this",
"->",
"unpackEncryptedBase64Data",
"(",
"$",
"encryptedBase64Data",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"hmacIsVal... | Decrypt RNCryptor-encrypted data
@param string $base64EncryptedData Encrypted, Base64-encoded text
@param string $password Password the text was encoded with
@throws Exception If the detected version is unsupported
@return string|false Decrypted string, or false if decryption failed | [
"Decrypt",
"RNCryptor",
"-",
"encrypted",
"data"
] | bf07c357461994b223bb4e3433cf442902f6e68b | https://github.com/RNCryptor/RNCryptor-php/blob/bf07c357461994b223bb4e3433cf442902f6e68b/src/RNCryptor/Decryptor.php#L22-L39 | train |
serverfireteam/blog | src/models/Blog.php | Blog.getUrl | function getUrl(){
return \Config::get('app.url') .'/blog/post/'. $this->id . '/' . \Serverfireteam\blog\BlogController::seoUrl($this->title);
} | php | function getUrl(){
return \Config::get('app.url') .'/blog/post/'. $this->id . '/' . \Serverfireteam\blog\BlogController::seoUrl($this->title);
} | [
"function",
"getUrl",
"(",
")",
"{",
"return",
"\\",
"Config",
"::",
"get",
"(",
"'app.url'",
")",
".",
"'/blog/post/'",
".",
"$",
"this",
"->",
"id",
".",
"'/'",
".",
"\\",
"Serverfireteam",
"\\",
"blog",
"\\",
"BlogController",
"::",
"seoUrl",
"(",
"... | return url of blog post | [
"return",
"url",
"of",
"blog",
"post"
] | d6f7aadc51b21b5ac9d216aa06615e680c5eb20f | https://github.com/serverfireteam/blog/blob/d6f7aadc51b21b5ac9d216aa06615e680c5eb20f/src/models/Blog.php#L19-L21 | train |
serverfireteam/blog | src/controllers/BlogController.php | BlogController.getShare | public function getShare($id,$social)
{
$url = '';
$post = \App\Blog::find($id);
if($post == NULL){
App::abort(404);
}
// add social point if it is not robot
if (!isset($_SERVER['HTTP_USER_AGENT']) && !preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) {
$post->socialPoint ++;
$post->save();
}
switch ($social){
case 'twitter' :
$url = 'https://twitter.com/home?status=';
$url .= $post['title'] . ' ' . $post->getUrl();
break;
case 'facebook' :
$url = 'https://www.facebook.com/sharer/sharer.php?u=';
$url .= $post->getUrl();
break;
case 'googlePlus' :
$url = 'https://plus.google.com/share?url=';
$url .= $post->getUrl();
break;
case 'linkedIn' :
$url = 'https://www.linkedin.com/shareArticle?mini=true&';
$url .= 'url='.$post->getUrl().'&title='.$post['title'].'&summary=&source=';
break;
}
return \Redirect::to($url);
} | php | public function getShare($id,$social)
{
$url = '';
$post = \App\Blog::find($id);
if($post == NULL){
App::abort(404);
}
// add social point if it is not robot
if (!isset($_SERVER['HTTP_USER_AGENT']) && !preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) {
$post->socialPoint ++;
$post->save();
}
switch ($social){
case 'twitter' :
$url = 'https://twitter.com/home?status=';
$url .= $post['title'] . ' ' . $post->getUrl();
break;
case 'facebook' :
$url = 'https://www.facebook.com/sharer/sharer.php?u=';
$url .= $post->getUrl();
break;
case 'googlePlus' :
$url = 'https://plus.google.com/share?url=';
$url .= $post->getUrl();
break;
case 'linkedIn' :
$url = 'https://www.linkedin.com/shareArticle?mini=true&';
$url .= 'url='.$post->getUrl().'&title='.$post['title'].'&summary=&source=';
break;
}
return \Redirect::to($url);
} | [
"public",
"function",
"getShare",
"(",
"$",
"id",
",",
"$",
"social",
")",
"{",
"$",
"url",
"=",
"''",
";",
"$",
"post",
"=",
"\\",
"App",
"\\",
"Blog",
"::",
"find",
"(",
"$",
"id",
")",
";",
"if",
"(",
"$",
"post",
"==",
"NULL",
")",
"{",
... | Add the point to | [
"Add",
"the",
"point",
"to"
] | d6f7aadc51b21b5ac9d216aa06615e680c5eb20f | https://github.com/serverfireteam/blog/blob/d6f7aadc51b21b5ac9d216aa06615e680c5eb20f/src/controllers/BlogController.php#L57-L89 | train |
ollyxar/websockets | src/Handler.php | Handler.listenSocket | protected function listenSocket(): Generator
{
yield Dispatcher::listenRead($this->server);
$handle = fopen($this->locker, 'a');
if ($handle && flock($handle, LOCK_EX)) {
yield Dispatcher::async($this->acceptSocket());
flock($handle, LOCK_UN);
}
fclose($handle);
yield Dispatcher::async($this->listenSocket());
} | php | protected function listenSocket(): Generator
{
yield Dispatcher::listenRead($this->server);
$handle = fopen($this->locker, 'a');
if ($handle && flock($handle, LOCK_EX)) {
yield Dispatcher::async($this->acceptSocket());
flock($handle, LOCK_UN);
}
fclose($handle);
yield Dispatcher::async($this->listenSocket());
} | [
"protected",
"function",
"listenSocket",
"(",
")",
":",
"Generator",
"{",
"yield",
"Dispatcher",
"::",
"listenRead",
"(",
"$",
"this",
"->",
"server",
")",
";",
"$",
"handle",
"=",
"fopen",
"(",
"$",
"this",
"->",
"locker",
",",
"'a'",
")",
";",
"if",
... | Main socket listener
@return Generator | [
"Main",
"socket",
"listener"
] | 2c5972f3ad37b682620661306c866ecebb048be4 | https://github.com/ollyxar/websockets/blob/2c5972f3ad37b682620661306c866ecebb048be4/src/Handler.php#L185-L197 | train |
ollyxar/websockets | src/Handler.php | Handler.afterHandshake | protected function afterHandshake($socket): Generator
{
Logger::log('worker', $this->pid, 'connection accepted for', (int)$socket);
$this->clients[(int)$socket] = $socket;
yield Dispatcher::async($this->onConnect($socket));
yield Dispatcher::async($this->read($socket));
} | php | protected function afterHandshake($socket): Generator
{
Logger::log('worker', $this->pid, 'connection accepted for', (int)$socket);
$this->clients[(int)$socket] = $socket;
yield Dispatcher::async($this->onConnect($socket));
yield Dispatcher::async($this->read($socket));
} | [
"protected",
"function",
"afterHandshake",
"(",
"$",
"socket",
")",
":",
"Generator",
"{",
"Logger",
"::",
"log",
"(",
"'worker'",
",",
"$",
"this",
"->",
"pid",
",",
"'connection accepted for'",
",",
"(",
"int",
")",
"$",
"socket",
")",
";",
"$",
"this"... | Process headers after handshake success
@param $socket
@return Generator | [
"Process",
"headers",
"after",
"handshake",
"success"
] | 2c5972f3ad37b682620661306c866ecebb048be4 | https://github.com/ollyxar/websockets/blob/2c5972f3ad37b682620661306c866ecebb048be4/src/Handler.php#L217-L223 | train |
ollyxar/websockets | src/Handler.php | Handler.onMasterMessage | protected function onMasterMessage(string $message): Generator
{
yield Dispatcher::async($this->broadcast(Frame::encode($message), false));
} | php | protected function onMasterMessage(string $message): Generator
{
yield Dispatcher::async($this->broadcast(Frame::encode($message), false));
} | [
"protected",
"function",
"onMasterMessage",
"(",
"string",
"$",
"message",
")",
":",
"Generator",
"{",
"yield",
"Dispatcher",
"::",
"async",
"(",
"$",
"this",
"->",
"broadcast",
"(",
"Frame",
"::",
"encode",
"(",
"$",
"message",
")",
",",
"false",
")",
"... | This method called when message received from the Master.
@param string $message
@return Generator | [
"This",
"method",
"called",
"when",
"message",
"received",
"from",
"the",
"Master",
"."
] | 2c5972f3ad37b682620661306c866ecebb048be4 | https://github.com/ollyxar/websockets/blob/2c5972f3ad37b682620661306c866ecebb048be4/src/Handler.php#L259-L262 | train |
stevenmaguire/uber-php | src/GetSetTrait.php | GetSetTrait.updateAttribute | private function updateAttribute($attribute, $value)
{
if (property_exists($this, $attribute)) {
$this->$attribute = $value;
}
return $this;
} | php | private function updateAttribute($attribute, $value)
{
if (property_exists($this, $attribute)) {
$this->$attribute = $value;
}
return $this;
} | [
"private",
"function",
"updateAttribute",
"(",
"$",
"attribute",
",",
"$",
"value",
")",
"{",
"if",
"(",
"property_exists",
"(",
"$",
"this",
",",
"$",
"attribute",
")",
")",
"{",
"$",
"this",
"->",
"$",
"attribute",
"=",
"$",
"value",
";",
"}",
"ret... | Updates a specific attribute of the current object.
@param string $attribute
@param string|boolean|integer $value
@return object | [
"Updates",
"a",
"specific",
"attribute",
"of",
"the",
"current",
"object",
"."
] | 6a5710dda83102aaef23c8f14e73a493d58963e9 | https://github.com/stevenmaguire/uber-php/blob/6a5710dda83102aaef23c8f14e73a493d58963e9/src/GetSetTrait.php#L89-L96 | train |
rakuten-ws/rws-php-sdk | lib/RakutenRws/Client.php | RakutenRws_Client.getAuthorizeUrl | public function getAuthorizeUrl($scope)
{
$url = 'https://app.rakuten.co.jp/services/authorize';
$parameter = array();
$parameter = array(
'response_type' => 'code',
'client_id' => $this->developerId,
'redirect_uri' => $this->redirectUrl,
'scope' => $scope
);
return $url.'?'.http_build_query($parameter);
} | php | public function getAuthorizeUrl($scope)
{
$url = 'https://app.rakuten.co.jp/services/authorize';
$parameter = array();
$parameter = array(
'response_type' => 'code',
'client_id' => $this->developerId,
'redirect_uri' => $this->redirectUrl,
'scope' => $scope
);
return $url.'?'.http_build_query($parameter);
} | [
"public",
"function",
"getAuthorizeUrl",
"(",
"$",
"scope",
")",
"{",
"$",
"url",
"=",
"'https://app.rakuten.co.jp/services/authorize'",
";",
"$",
"parameter",
"=",
"array",
"(",
")",
";",
"$",
"parameter",
"=",
"array",
"(",
"'response_type'",
"=>",
"'code'",
... | Gets OAuth2 Authorize URL
@param string $scope The scopes that is separated by ','
@return string The Authorize URL | [
"Gets",
"OAuth2",
"Authorize",
"URL"
] | ca9c78d8f3bc8714a4366a9a3a247bc2788a41eb | https://github.com/rakuten-ws/rws-php-sdk/blob/ca9c78d8f3bc8714a4366a9a3a247bc2788a41eb/lib/RakutenRws/Client.php#L136-L148 | train |
rakuten-ws/rws-php-sdk | lib/RakutenRws/Client.php | RakutenRws_Client.fetchAccessTokenFromCode | public function fetchAccessTokenFromCode($code = null)
{
if ($code === null) {
if (!isset($_GET['code'])) {
throw new LogicException("A parameter code is not set.");
}
$code = $_GET['code'];
}
$url = $this->getAccessTokenUrl();
$parameter = array(
'grant_type' => 'authorization_code',
'client_id' => $this->developerId,
'client_secret' => $this->secret,
'code' => $code,
'redirect_uri' => $this->redirectUrl
);
$response = $this->httpClient->post(
$url,
$parameter
);
if ($response->getCode() == 200) {
$this->accessTokenInfo = json_decode($response->getContents(), true);
if (isset($this->accessTokenInfo['access_token'])) {
$this->accessToken = $this->accessTokenInfo['access_token'];
return $this->accessToken;
}
}
return null;
} | php | public function fetchAccessTokenFromCode($code = null)
{
if ($code === null) {
if (!isset($_GET['code'])) {
throw new LogicException("A parameter code is not set.");
}
$code = $_GET['code'];
}
$url = $this->getAccessTokenUrl();
$parameter = array(
'grant_type' => 'authorization_code',
'client_id' => $this->developerId,
'client_secret' => $this->secret,
'code' => $code,
'redirect_uri' => $this->redirectUrl
);
$response = $this->httpClient->post(
$url,
$parameter
);
if ($response->getCode() == 200) {
$this->accessTokenInfo = json_decode($response->getContents(), true);
if (isset($this->accessTokenInfo['access_token'])) {
$this->accessToken = $this->accessTokenInfo['access_token'];
return $this->accessToken;
}
}
return null;
} | [
"public",
"function",
"fetchAccessTokenFromCode",
"(",
"$",
"code",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"code",
"===",
"null",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"_GET",
"[",
"'code'",
"]",
")",
")",
"{",
"throw",
"new",
"LogicException"... | Fetches OAuth2 AccessToken from Code
@param string $code The Code
@return string The Access Token, If response is invalid return null
@throws LogicException | [
"Fetches",
"OAuth2",
"AccessToken",
"from",
"Code"
] | ca9c78d8f3bc8714a4366a9a3a247bc2788a41eb | https://github.com/rakuten-ws/rws-php-sdk/blob/ca9c78d8f3bc8714a4366a9a3a247bc2788a41eb/lib/RakutenRws/Client.php#L167-L201 | train |
ollyxar/websockets | src/Server.php | Server.makeSocket | protected function makeSocket(): void
{
if ($this->useSSL) {
if (!file_exists($this->cert)) {
throw new \Exception('Cert file not found');
}
$context = stream_context_create([
'ssl' => [
'local_cert' => $this->cert,
'passphrase' => $this->passPhrase,
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
'verify_depth' => 0
]
]);
$protocol = 'ssl';
} else {
$context = stream_context_create();
$protocol = 'tcp';
}
$this->socket = stream_socket_server("$protocol://{$this->host}:{$this->port}", $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);
if ($this->useConnector) {
if (file_exists(static::$connector)) {
unlink(static::$connector);
}
$this->unixConnector = stream_socket_server('unix://' . static::$connector, $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
chmod(static::$connector, 0777);
}
if (!$this->socket) {
throw new SocketException($errorString, $errorNumber);
}
} | php | protected function makeSocket(): void
{
if ($this->useSSL) {
if (!file_exists($this->cert)) {
throw new \Exception('Cert file not found');
}
$context = stream_context_create([
'ssl' => [
'local_cert' => $this->cert,
'passphrase' => $this->passPhrase,
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
'verify_depth' => 0
]
]);
$protocol = 'ssl';
} else {
$context = stream_context_create();
$protocol = 'tcp';
}
$this->socket = stream_socket_server("$protocol://{$this->host}:{$this->port}", $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);
if ($this->useConnector) {
if (file_exists(static::$connector)) {
unlink(static::$connector);
}
$this->unixConnector = stream_socket_server('unix://' . static::$connector, $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
chmod(static::$connector, 0777);
}
if (!$this->socket) {
throw new SocketException($errorString, $errorNumber);
}
} | [
"protected",
"function",
"makeSocket",
"(",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"useSSL",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"this",
"->",
"cert",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Cert file not... | Make server sockets
@throws SocketException|\Exception
@return void | [
"Make",
"server",
"sockets"
] | 2c5972f3ad37b682620661306c866ecebb048be4 | https://github.com/ollyxar/websockets/blob/2c5972f3ad37b682620661306c866ecebb048be4/src/Server.php#L64-L102 | train |
ollyxar/websockets | src/Server.php | Server.spawn | protected function spawn(): array
{
$pid = $master = null;
$workers = [];
for ($i = 0; $i < $this->workerCount; $i++) {
$pair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
$pid = pcntl_fork();
if ($pid == -1) {
throw new ForkException('Cannot fork process');
} elseif ($pid) {
fclose($pair[0]);
$workers[$pid] = $pair[1];
} else {
fclose($pair[1]);
$master = $pair[0];
break;
}
}
return [$pid, $master, $workers];
} | php | protected function spawn(): array
{
$pid = $master = null;
$workers = [];
for ($i = 0; $i < $this->workerCount; $i++) {
$pair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
$pid = pcntl_fork();
if ($pid == -1) {
throw new ForkException('Cannot fork process');
} elseif ($pid) {
fclose($pair[0]);
$workers[$pid] = $pair[1];
} else {
fclose($pair[1]);
$master = $pair[0];
break;
}
}
return [$pid, $master, $workers];
} | [
"protected",
"function",
"spawn",
"(",
")",
":",
"array",
"{",
"$",
"pid",
"=",
"$",
"master",
"=",
"null",
";",
"$",
"workers",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"this",
"->",
"workerCount",
";",
"$... | Spawning process to avoid system limits and increase performance
@throws ForkException
@return array | [
"Spawning",
"process",
"to",
"avoid",
"system",
"limits",
"and",
"increase",
"performance"
] | 2c5972f3ad37b682620661306c866ecebb048be4 | https://github.com/ollyxar/websockets/blob/2c5972f3ad37b682620661306c866ecebb048be4/src/Server.php#L110-L133 | train |
ollyxar/websockets | src/Server.php | Server.handleSignals | protected function handleSignals(): void
{
foreach ([SIGTERM, SIGQUIT, SIGABRT, SIGINT] as $signal) {
pcntl_signal($signal, function ($signal) {
$this->terminate($signal);
});
}
} | php | protected function handleSignals(): void
{
foreach ([SIGTERM, SIGQUIT, SIGABRT, SIGINT] as $signal) {
pcntl_signal($signal, function ($signal) {
$this->terminate($signal);
});
}
} | [
"protected",
"function",
"handleSignals",
"(",
")",
":",
"void",
"{",
"foreach",
"(",
"[",
"SIGTERM",
",",
"SIGQUIT",
",",
"SIGABRT",
",",
"SIGINT",
"]",
"as",
"$",
"signal",
")",
"{",
"pcntl_signal",
"(",
"$",
"signal",
",",
"function",
"(",
"$",
"sig... | Process system signals
@return void | [
"Process",
"system",
"signals"
] | 2c5972f3ad37b682620661306c866ecebb048be4 | https://github.com/ollyxar/websockets/blob/2c5972f3ad37b682620661306c866ecebb048be4/src/Server.php#L155-L162 | train |
ollyxar/websockets | src/Logger.php | Logger.log | public static function log($speakerType, $speakerId, $message, $raw = ''): void
{
if (!static::$enabled) {
return;
}
switch ($speakerType) {
case 'master':
$speaker = "\033[1;34m" . $speakerId . "\033[0m";
break;
default:
$speaker = "\033[1;35m" . $speakerId . "\033[0m";
}
$log = "\033[1;37m";
try {
$log .= \DateTime::createFromFormat('U.u', microtime(true))->format("i:s:u");
} catch (\Throwable $exception) {
$log .= 'cannot get current time. God damn fast!';
}
$log .= "\033[0m ";
$log .= $speaker . " ";
$log .= "\033[1;32m" . $message . "\033[0m ";
$log .= "\033[42m" . $raw . "\033[0m\n";
print $log;
} | php | public static function log($speakerType, $speakerId, $message, $raw = ''): void
{
if (!static::$enabled) {
return;
}
switch ($speakerType) {
case 'master':
$speaker = "\033[1;34m" . $speakerId . "\033[0m";
break;
default:
$speaker = "\033[1;35m" . $speakerId . "\033[0m";
}
$log = "\033[1;37m";
try {
$log .= \DateTime::createFromFormat('U.u', microtime(true))->format("i:s:u");
} catch (\Throwable $exception) {
$log .= 'cannot get current time. God damn fast!';
}
$log .= "\033[0m ";
$log .= $speaker . " ";
$log .= "\033[1;32m" . $message . "\033[0m ";
$log .= "\033[42m" . $raw . "\033[0m\n";
print $log;
} | [
"public",
"static",
"function",
"log",
"(",
"$",
"speakerType",
",",
"$",
"speakerId",
",",
"$",
"message",
",",
"$",
"raw",
"=",
"''",
")",
":",
"void",
"{",
"if",
"(",
"!",
"static",
"::",
"$",
"enabled",
")",
"{",
"return",
";",
"}",
"switch",
... | Printing info into console
@param $speakerType
@param $speakerId
@param $message
@param string $raw
@return void | [
"Printing",
"info",
"into",
"console"
] | 2c5972f3ad37b682620661306c866ecebb048be4 | https://github.com/ollyxar/websockets/blob/2c5972f3ad37b682620661306c866ecebb048be4/src/Logger.php#L41-L68 | train |
stevenmaguire/uber-php | src/Client.php | Client.applyConfiguration | private function applyConfiguration($configuration = [])
{
array_walk($configuration, function ($value, $key) {
$this->updateAttribute($key, $value);
});
} | php | private function applyConfiguration($configuration = [])
{
array_walk($configuration, function ($value, $key) {
$this->updateAttribute($key, $value);
});
} | [
"private",
"function",
"applyConfiguration",
"(",
"$",
"configuration",
"=",
"[",
"]",
")",
"{",
"array_walk",
"(",
"$",
"configuration",
",",
"function",
"(",
"$",
"value",
",",
"$",
"key",
")",
"{",
"$",
"this",
"->",
"updateAttribute",
"(",
"$",
"key"... | Applies configuration to client.
@param array $configuration
@return void | [
"Applies",
"configuration",
"to",
"client",
"."
] | 6a5710dda83102aaef23c8f14e73a493d58963e9 | https://github.com/stevenmaguire/uber-php/blob/6a5710dda83102aaef23c8f14e73a493d58963e9/src/Client.php#L87-L92 | train |
stevenmaguire/uber-php | src/Client.php | Client.getConfigForVerbAndParameters | private function getConfigForVerbAndParameters($verb, $parameters = [])
{
$config = [
'headers' => $this->getHeaders()
];
if (!empty($parameters)) {
if (strtolower($verb) == 'get') {
$config['query'] = $parameters;
} else {
$config['json'] = $parameters;
}
}
return $config;
} | php | private function getConfigForVerbAndParameters($verb, $parameters = [])
{
$config = [
'headers' => $this->getHeaders()
];
if (!empty($parameters)) {
if (strtolower($verb) == 'get') {
$config['query'] = $parameters;
} else {
$config['json'] = $parameters;
}
}
return $config;
} | [
"private",
"function",
"getConfigForVerbAndParameters",
"(",
"$",
"verb",
",",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"$",
"config",
"=",
"[",
"'headers'",
"=>",
"$",
"this",
"->",
"getHeaders",
"(",
")",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
... | Gets HttpClient config for verb and parameters.
@param string $verb
@param array $parameters
@return array | [
"Gets",
"HttpClient",
"config",
"for",
"verb",
"and",
"parameters",
"."
] | 6a5710dda83102aaef23c8f14e73a493d58963e9 | https://github.com/stevenmaguire/uber-php/blob/6a5710dda83102aaef23c8f14e73a493d58963e9/src/Client.php#L116-L131 | train |
stevenmaguire/uber-php | src/Client.php | Client.getUrlFromPath | public function getUrlFromPath($path)
{
$path = ltrim($path, '/');
$host = 'https://'.($this->use_sandbox ? 'sandbox-' : '').'api.uber.com';
return $host.($this->version ? '/'.$this->version : '').'/'.$path;
} | php | public function getUrlFromPath($path)
{
$path = ltrim($path, '/');
$host = 'https://'.($this->use_sandbox ? 'sandbox-' : '').'api.uber.com';
return $host.($this->version ? '/'.$this->version : '').'/'.$path;
} | [
"public",
"function",
"getUrlFromPath",
"(",
"$",
"path",
")",
"{",
"$",
"path",
"=",
"ltrim",
"(",
"$",
"path",
",",
"'/'",
")",
";",
"$",
"host",
"=",
"'https://'",
".",
"(",
"$",
"this",
"->",
"use_sandbox",
"?",
"'sandbox-'",
":",
"''",
")",
".... | Builds url from path.
@param string $path
@return string Url | [
"Builds",
"url",
"from",
"path",
"."
] | 6a5710dda83102aaef23c8f14e73a493d58963e9 | https://github.com/stevenmaguire/uber-php/blob/6a5710dda83102aaef23c8f14e73a493d58963e9/src/Client.php#L153-L160 | train |
stevenmaguire/uber-php | src/Client.php | Client.handleRequestException | private function handleRequestException(HttpClientException $e)
{
if ($response = $e->getResponse()) {
$exception = new Exception($response->getReasonPhrase(), $response->getStatusCode(), $e);
$exception->setBody(json_decode($response->getBody()));
throw $exception;
}
throw new Exception($e->getMessage(), 500, $e);
} | php | private function handleRequestException(HttpClientException $e)
{
if ($response = $e->getResponse()) {
$exception = new Exception($response->getReasonPhrase(), $response->getStatusCode(), $e);
$exception->setBody(json_decode($response->getBody()));
throw $exception;
}
throw new Exception($e->getMessage(), 500, $e);
} | [
"private",
"function",
"handleRequestException",
"(",
"HttpClientException",
"$",
"e",
")",
"{",
"if",
"(",
"$",
"response",
"=",
"$",
"e",
"->",
"getResponse",
"(",
")",
")",
"{",
"$",
"exception",
"=",
"new",
"Exception",
"(",
"$",
"response",
"->",
"g... | Handles http client exceptions.
@param HttpClientException $e
@return void
@throws Exception | [
"Handles",
"http",
"client",
"exceptions",
"."
] | 6a5710dda83102aaef23c8f14e73a493d58963e9 | https://github.com/stevenmaguire/uber-php/blob/6a5710dda83102aaef23c8f14e73a493d58963e9/src/Client.php#L170-L180 | train |
stevenmaguire/uber-php | src/Client.php | Client.parseRateLimitFromResponse | private function parseRateLimitFromResponse(Response $response)
{
$rateLimitHeaders = array_filter([
$response->getHeader('X-Rate-Limit-Limit'),
$response->getHeader('X-Rate-Limit-Remaining'),
$response->getHeader('X-Rate-Limit-Reset')
]);
if (count($rateLimitHeaders) == 3) {
$rateLimitClass = new ReflectionClass(RateLimit::class);
$this->rate_limit = $rateLimitClass->newInstanceArgs($rateLimitHeaders);
}
} | php | private function parseRateLimitFromResponse(Response $response)
{
$rateLimitHeaders = array_filter([
$response->getHeader('X-Rate-Limit-Limit'),
$response->getHeader('X-Rate-Limit-Remaining'),
$response->getHeader('X-Rate-Limit-Reset')
]);
if (count($rateLimitHeaders) == 3) {
$rateLimitClass = new ReflectionClass(RateLimit::class);
$this->rate_limit = $rateLimitClass->newInstanceArgs($rateLimitHeaders);
}
} | [
"private",
"function",
"parseRateLimitFromResponse",
"(",
"Response",
"$",
"response",
")",
"{",
"$",
"rateLimitHeaders",
"=",
"array_filter",
"(",
"[",
"$",
"response",
"->",
"getHeader",
"(",
"'X-Rate-Limit-Limit'",
")",
",",
"$",
"response",
"->",
"getHeader",
... | Attempts to pull rate limit headers from response and add to client.
@param Response $response
@return void | [
"Attempts",
"to",
"pull",
"rate",
"limit",
"headers",
"from",
"response",
"and",
"add",
"to",
"client",
"."
] | 6a5710dda83102aaef23c8f14e73a493d58963e9 | https://github.com/stevenmaguire/uber-php/blob/6a5710dda83102aaef23c8f14e73a493d58963e9/src/Client.php#L209-L221 | train |
stevenmaguire/uber-php | src/Client.php | Client.request | protected function request($verb, $path, $parameters = [])
{
$client = $this->httpClient;
$url = $this->getUrlFromPath($path);
$verb = strtolower($verb);
$config = $this->getConfigForVerbAndParameters($verb, $parameters);
try {
$response = $client->$verb($url, $config);
} catch (HttpClientException $e) {
$this->handleRequestException($e);
}
$this->parseRateLimitFromResponse($response);
return json_decode($response->getBody());
} | php | protected function request($verb, $path, $parameters = [])
{
$client = $this->httpClient;
$url = $this->getUrlFromPath($path);
$verb = strtolower($verb);
$config = $this->getConfigForVerbAndParameters($verb, $parameters);
try {
$response = $client->$verb($url, $config);
} catch (HttpClientException $e) {
$this->handleRequestException($e);
}
$this->parseRateLimitFromResponse($response);
return json_decode($response->getBody());
} | [
"protected",
"function",
"request",
"(",
"$",
"verb",
",",
"$",
"path",
",",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"$",
"client",
"=",
"$",
"this",
"->",
"httpClient",
";",
"$",
"url",
"=",
"$",
"this",
"->",
"getUrlFromPath",
"(",
"$",
"path... | Makes a request to the Uber API and returns the response.
@param string $verb The Http verb to use
@param string $path The path of the APi after the domain
@param array $parameters Parameters
@return stdClass The JSON response from the request
@throws Exception | [
"Makes",
"a",
"request",
"to",
"the",
"Uber",
"API",
"and",
"returns",
"the",
"response",
"."
] | 6a5710dda83102aaef23c8f14e73a493d58963e9 | https://github.com/stevenmaguire/uber-php/blob/6a5710dda83102aaef23c8f14e73a493d58963e9/src/Client.php#L233-L249 | train |
machour/yii2-notifications | commands/NotificationsController.php | NotificationsController.actionClean | public function actionClean()
{
$class = $this->module->notificationClass;
// Delete all notifications seen or flashed
$criteria = ['or', ['seen=1'], ['flashed=1']];
// Delete old notification according to expiration time setting
if ( $this->module->expirationTime > 0 ) {
$criteria[] = ['<', 'created_at', time()-$this->module->expirationTime ];
}
$records_deleted = $class::deleteAll($criteria);
echo "$records_deleted obsolete notifications removed\n";
} | php | public function actionClean()
{
$class = $this->module->notificationClass;
// Delete all notifications seen or flashed
$criteria = ['or', ['seen=1'], ['flashed=1']];
// Delete old notification according to expiration time setting
if ( $this->module->expirationTime > 0 ) {
$criteria[] = ['<', 'created_at', time()-$this->module->expirationTime ];
}
$records_deleted = $class::deleteAll($criteria);
echo "$records_deleted obsolete notifications removed\n";
} | [
"public",
"function",
"actionClean",
"(",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"module",
"->",
"notificationClass",
";",
"// Delete all notifications seen or flashed",
"$",
"criteria",
"=",
"[",
"'or'",
",",
"[",
"'seen=1'",
"]",
",",
"[",
"'flashed... | Clean obsolete notifications | [
"Clean",
"obsolete",
"notifications"
] | 56c1dcb593c024f06ce4701818096e20c845e950 | https://github.com/machour/yii2-notifications/blob/56c1dcb593c024f06ce4701818096e20c845e950/commands/NotificationsController.php#L14-L29 | train |
machour/yii2-notifications | models/Notification.php | Notification.warning | public static function warning($key, $user_id, $key_id = null)
{
return static::notify($key, $user_id, $key_id, self::TYPE_WARNING);
} | php | public static function warning($key, $user_id, $key_id = null)
{
return static::notify($key, $user_id, $key_id, self::TYPE_WARNING);
} | [
"public",
"static",
"function",
"warning",
"(",
"$",
"key",
",",
"$",
"user_id",
",",
"$",
"key_id",
"=",
"null",
")",
"{",
"return",
"static",
"::",
"notify",
"(",
"$",
"key",
",",
"$",
"user_id",
",",
"$",
"key_id",
",",
"self",
"::",
"TYPE_WARNING... | Creates a warning notification
@param string $key
@param integer $user_id The user id that will get the notification
@param string $key_id The notification key id
@return bool Returns TRUE on success, FALSE on failure | [
"Creates",
"a",
"warning",
"notification"
] | 56c1dcb593c024f06ce4701818096e20c845e950 | https://github.com/machour/yii2-notifications/blob/56c1dcb593c024f06ce4701818096e20c845e950/models/Notification.php#L117-L120 | train |
machour/yii2-notifications | models/Notification.php | Notification.error | public static function error($key, $user_id, $key_id = null)
{
return static::notify($key, $user_id, $key_id, self::TYPE_ERROR);
} | php | public static function error($key, $user_id, $key_id = null)
{
return static::notify($key, $user_id, $key_id, self::TYPE_ERROR);
} | [
"public",
"static",
"function",
"error",
"(",
"$",
"key",
",",
"$",
"user_id",
",",
"$",
"key_id",
"=",
"null",
")",
"{",
"return",
"static",
"::",
"notify",
"(",
"$",
"key",
",",
"$",
"user_id",
",",
"$",
"key_id",
",",
"self",
"::",
"TYPE_ERROR",
... | Creates an error notification
@param string $key
@param integer $user_id The user id that will get the notification
@param string $key_id The notification key id
@return bool Returns TRUE on success, FALSE on failure | [
"Creates",
"an",
"error",
"notification"
] | 56c1dcb593c024f06ce4701818096e20c845e950 | https://github.com/machour/yii2-notifications/blob/56c1dcb593c024f06ce4701818096e20c845e950/models/Notification.php#L131-L134 | train |
machour/yii2-notifications | models/Notification.php | Notification.success | public static function success($key, $user_id, $key_id = null)
{
return static::notify($key, $user_id, $key_id, self::TYPE_SUCCESS);
} | php | public static function success($key, $user_id, $key_id = null)
{
return static::notify($key, $user_id, $key_id, self::TYPE_SUCCESS);
} | [
"public",
"static",
"function",
"success",
"(",
"$",
"key",
",",
"$",
"user_id",
",",
"$",
"key_id",
"=",
"null",
")",
"{",
"return",
"static",
"::",
"notify",
"(",
"$",
"key",
",",
"$",
"user_id",
",",
"$",
"key_id",
",",
"self",
"::",
"TYPE_SUCCESS... | Creates a success notification
@param string $key
@param integer $user_id The user id that will get the notification
@param string $key_id The notification key id
@return bool Returns TRUE on success, FALSE on failure | [
"Creates",
"a",
"success",
"notification"
] | 56c1dcb593c024f06ce4701818096e20c845e950 | https://github.com/machour/yii2-notifications/blob/56c1dcb593c024f06ce4701818096e20c845e950/models/Notification.php#L145-L148 | train |
machour/yii2-notifications | widgets/NotificationsAsset.php | NotificationsAsset.getFilename | public static function getFilename($theme, $type)
{
$filename = 'themes/' . $theme . '.' . $type;
if (file_exists(Yii::getAlias(self::$assetsDirectory) . $filename)) {
return $filename;
}
return false;
} | php | public static function getFilename($theme, $type)
{
$filename = 'themes/' . $theme . '.' . $type;
if (file_exists(Yii::getAlias(self::$assetsDirectory) . $filename)) {
return $filename;
}
return false;
} | [
"public",
"static",
"function",
"getFilename",
"(",
"$",
"theme",
",",
"$",
"type",
")",
"{",
"$",
"filename",
"=",
"'themes/'",
".",
"$",
"theme",
".",
"'.'",
".",
"$",
"type",
";",
"if",
"(",
"file_exists",
"(",
"Yii",
"::",
"getAlias",
"(",
"self"... | Gets the required theme filename if it exists
@param string $theme The theme name
@param string $type The resource type. Either "js" or "css"
@return bool|string Returns the filename if it exists, or FALSE. | [
"Gets",
"the",
"required",
"theme",
"filename",
"if",
"it",
"exists"
] | 56c1dcb593c024f06ce4701818096e20c845e950 | https://github.com/machour/yii2-notifications/blob/56c1dcb593c024f06ce4701818096e20c845e950/widgets/NotificationsAsset.php#L60-L67 | train |
machour/yii2-notifications | widgets/NotificationsAsset.php | NotificationsAsset.getTimeAgoI18n | public static function getTimeAgoI18n($locale)
{
$pattern = 'locales/jquery.timeago.%s.js';
$filename = sprintf($pattern, $locale);
if (file_exists(Yii::getAlias(self::$assetsDirectory) . $filename)) {
return $filename;
} else { // try harder by shortening the locale
$locale = substr($locale, 0, 2);
$filename = sprintf($pattern, $locale);
if (file_exists(Yii::getAlias(self::$assetsDirectory) . $filename)) {
return $filename;
}
}
return false;
} | php | public static function getTimeAgoI18n($locale)
{
$pattern = 'locales/jquery.timeago.%s.js';
$filename = sprintf($pattern, $locale);
if (file_exists(Yii::getAlias(self::$assetsDirectory) . $filename)) {
return $filename;
} else { // try harder by shortening the locale
$locale = substr($locale, 0, 2);
$filename = sprintf($pattern, $locale);
if (file_exists(Yii::getAlias(self::$assetsDirectory) . $filename)) {
return $filename;
}
}
return false;
} | [
"public",
"static",
"function",
"getTimeAgoI18n",
"(",
"$",
"locale",
")",
"{",
"$",
"pattern",
"=",
"'locales/jquery.timeago.%s.js'",
";",
"$",
"filename",
"=",
"sprintf",
"(",
"$",
"pattern",
",",
"$",
"locale",
")",
";",
"if",
"(",
"file_exists",
"(",
"... | Gets the jQuery timeago locale file based on the current Yii language
@return bool|string Returns the path to the locale file, or FALSE if
it does not exist. | [
"Gets",
"the",
"jQuery",
"timeago",
"locale",
"file",
"based",
"on",
"the",
"current",
"Yii",
"language"
] | 56c1dcb593c024f06ce4701818096e20c845e950 | https://github.com/machour/yii2-notifications/blob/56c1dcb593c024f06ce4701818096e20c845e950/widgets/NotificationsAsset.php#L75-L90 | train |
machour/yii2-notifications | controllers/NotificationsController.php | NotificationsController.actionRnr | public function actionRnr($id)
{
$notification = $this->actionRead($id);
return $this->redirect(Url::to($notification->getRoute()));
} | php | public function actionRnr($id)
{
$notification = $this->actionRead($id);
return $this->redirect(Url::to($notification->getRoute()));
} | [
"public",
"function",
"actionRnr",
"(",
"$",
"id",
")",
"{",
"$",
"notification",
"=",
"$",
"this",
"->",
"actionRead",
"(",
"$",
"id",
")",
";",
"return",
"$",
"this",
"->",
"redirect",
"(",
"Url",
"::",
"to",
"(",
"$",
"notification",
"->",
"getRou... | Marks a notification as read and redirects the user to the final route
@param int $id The notification id
@return Response
@throws HttpException Throws an exception if the notification is not
found, or if it don't belongs to the logged in user | [
"Marks",
"a",
"notification",
"as",
"read",
"and",
"redirects",
"the",
"user",
"to",
"the",
"final",
"route"
] | 56c1dcb593c024f06ce4701818096e20c845e950 | https://github.com/machour/yii2-notifications/blob/56c1dcb593c024f06ce4701818096e20c845e950/controllers/NotificationsController.php#L85-L89 | train |
machour/yii2-notifications | controllers/NotificationsController.php | NotificationsController.actionRead | public function actionRead($id)
{
$notification = $this->getNotification($id);
$notification->seen = 1;
$notification->save();
return $notification;
} | php | public function actionRead($id)
{
$notification = $this->getNotification($id);
$notification->seen = 1;
$notification->save();
return $notification;
} | [
"public",
"function",
"actionRead",
"(",
"$",
"id",
")",
"{",
"$",
"notification",
"=",
"$",
"this",
"->",
"getNotification",
"(",
"$",
"id",
")",
";",
"$",
"notification",
"->",
"seen",
"=",
"1",
";",
"$",
"notification",
"->",
"save",
"(",
")",
";"... | Marks a notification as read
@param int $id The notification id
@return Notification The updated notification record
@throws HttpException Throws an exception if the notification is not
found, or if it don't belongs to the logged in user | [
"Marks",
"a",
"notification",
"as",
"read"
] | 56c1dcb593c024f06ce4701818096e20c845e950 | https://github.com/machour/yii2-notifications/blob/56c1dcb593c024f06ce4701818096e20c845e950/controllers/NotificationsController.php#L99-L107 | train |
machour/yii2-notifications | controllers/NotificationsController.php | NotificationsController.actionReadAll | public function actionReadAll()
{
$notificationsIds = Yii::$app->request->post('ids', []);
foreach ($notificationsIds as $id) {
$notification = $this->getNotification($id);
$notification->seen = 1;
$notification->save();
}
return true;
} | php | public function actionReadAll()
{
$notificationsIds = Yii::$app->request->post('ids', []);
foreach ($notificationsIds as $id) {
$notification = $this->getNotification($id);
$notification->seen = 1;
$notification->save();
}
return true;
} | [
"public",
"function",
"actionReadAll",
"(",
")",
"{",
"$",
"notificationsIds",
"=",
"Yii",
"::",
"$",
"app",
"->",
"request",
"->",
"post",
"(",
"'ids'",
",",
"[",
"]",
")",
";",
"foreach",
"(",
"$",
"notificationsIds",
"as",
"$",
"id",
")",
"{",
"$"... | Marks all notification as read
@throws HttpException Throws an exception if the notification is not
found, or if it don't belongs to the logged in user | [
"Marks",
"all",
"notification",
"as",
"read"
] | 56c1dcb593c024f06ce4701818096e20c845e950 | https://github.com/machour/yii2-notifications/blob/56c1dcb593c024f06ce4701818096e20c845e950/controllers/NotificationsController.php#L115-L127 | train |
machour/yii2-notifications | controllers/NotificationsController.php | NotificationsController.actionDeleteAll | public function actionDeleteAll()
{
$notificationsIds = Yii::$app->request->post('ids', []);
foreach ($notificationsIds as $id) {
$notification = $this->getNotification($id);
$notification->delete();
}
return true;
} | php | public function actionDeleteAll()
{
$notificationsIds = Yii::$app->request->post('ids', []);
foreach ($notificationsIds as $id) {
$notification = $this->getNotification($id);
$notification->delete();
}
return true;
} | [
"public",
"function",
"actionDeleteAll",
"(",
")",
"{",
"$",
"notificationsIds",
"=",
"Yii",
"::",
"$",
"app",
"->",
"request",
"->",
"post",
"(",
"'ids'",
",",
"[",
"]",
")",
";",
"foreach",
"(",
"$",
"notificationsIds",
"as",
"$",
"id",
")",
"{",
"... | Delete all notifications
@throws HttpException Throws an exception if the notification is not
found, or if it don't belongs to the logged in user | [
"Delete",
"all",
"notifications"
] | 56c1dcb593c024f06ce4701818096e20c845e950 | https://github.com/machour/yii2-notifications/blob/56c1dcb593c024f06ce4701818096e20c845e950/controllers/NotificationsController.php#L135-L146 | train |
machour/yii2-notifications | controllers/NotificationsController.php | NotificationsController.getNotification | private function getNotification($id)
{
/** @var Notification $notification */
$class = $this->notificationClass;
$notification = $class::findOne($id);
if (!$notification) {
throw new HttpException(404, "Unknown notification");
}
if ($notification->user_id != $this->user_id) {
throw new HttpException(500, "Not your notification");
}
return $notification;
} | php | private function getNotification($id)
{
/** @var Notification $notification */
$class = $this->notificationClass;
$notification = $class::findOne($id);
if (!$notification) {
throw new HttpException(404, "Unknown notification");
}
if ($notification->user_id != $this->user_id) {
throw new HttpException(500, "Not your notification");
}
return $notification;
} | [
"private",
"function",
"getNotification",
"(",
"$",
"id",
")",
"{",
"/** @var Notification $notification */",
"$",
"class",
"=",
"$",
"this",
"->",
"notificationClass",
";",
"$",
"notification",
"=",
"$",
"class",
"::",
"findOne",
"(",
"$",
"id",
")",
";",
"... | Gets a notification by id
@param int $id The notification id
@return Notification
@throws HttpException Throws an exception if the notification is not
found, or if it don't belongs to the logged in user | [
"Gets",
"a",
"notification",
"by",
"id"
] | 56c1dcb593c024f06ce4701818096e20c845e950 | https://github.com/machour/yii2-notifications/blob/56c1dcb593c024f06ce4701818096e20c845e950/controllers/NotificationsController.php#L181-L195 | train |
shvetsgroup/laravel-email-database-log | src/ShvetsGroup/LaravelEmailDatabaseLog/EmailLogger.php | EmailLogger.formatAddressField | function formatAddressField($message, $field)
{
$headers = $message->getHeaders();
if (!$headers->has($field)) {
return null;
}
$mailboxes = $headers->get($field)->getFieldBodyModel();
$strings = [];
foreach ($mailboxes as $email => $name) {
$mailboxStr = $email;
if (null !== $name) {
$mailboxStr = $name . ' <' . $mailboxStr . '>';
}
$strings[] = $mailboxStr;
}
return implode(', ', $strings);
} | php | function formatAddressField($message, $field)
{
$headers = $message->getHeaders();
if (!$headers->has($field)) {
return null;
}
$mailboxes = $headers->get($field)->getFieldBodyModel();
$strings = [];
foreach ($mailboxes as $email => $name) {
$mailboxStr = $email;
if (null !== $name) {
$mailboxStr = $name . ' <' . $mailboxStr . '>';
}
$strings[] = $mailboxStr;
}
return implode(', ', $strings);
} | [
"function",
"formatAddressField",
"(",
"$",
"message",
",",
"$",
"field",
")",
"{",
"$",
"headers",
"=",
"$",
"message",
"->",
"getHeaders",
"(",
")",
";",
"if",
"(",
"!",
"$",
"headers",
"->",
"has",
"(",
"$",
"field",
")",
")",
"{",
"return",
"nu... | Format address strings for sender, to, cc, bcc.
@param $message
@param $field
@return null|string | [
"Format",
"address",
"strings",
"for",
"sender",
"to",
"cc",
"bcc",
"."
] | 8710cb82e0d69151fe632d450814c4e95367e022 | https://github.com/shvetsgroup/laravel-email-database-log/blob/8710cb82e0d69151fe632d450814c4e95367e022/src/ShvetsGroup/LaravelEmailDatabaseLog/EmailLogger.php#L39-L58 | train |
guillermomartinez/filemanager-laravel | src/Pqb/FilemanagerLaravel/plugins/rsc/cloudfiles.php | CF_Authentication.load_cached_credentials | function load_cached_credentials($auth_token, $storage_url, $cdnm_url)
{
if(!$storage_url || !$cdnm_url)
{
throw new SyntaxException("Missing Required Interface URL's!");
}
if(!$auth_token)
{
throw new SyntaxException("Missing Auth Token!");
}
$this->storage_url = $storage_url;
$this->cdnm_url = $cdnm_url;
$this->auth_token = $auth_token;
return True;
} | php | function load_cached_credentials($auth_token, $storage_url, $cdnm_url)
{
if(!$storage_url || !$cdnm_url)
{
throw new SyntaxException("Missing Required Interface URL's!");
}
if(!$auth_token)
{
throw new SyntaxException("Missing Auth Token!");
}
$this->storage_url = $storage_url;
$this->cdnm_url = $cdnm_url;
$this->auth_token = $auth_token;
return True;
} | [
"function",
"load_cached_credentials",
"(",
"$",
"auth_token",
",",
"$",
"storage_url",
",",
"$",
"cdnm_url",
")",
"{",
"if",
"(",
"!",
"$",
"storage_url",
"||",
"!",
"$",
"cdnm_url",
")",
"{",
"throw",
"new",
"SyntaxException",
"(",
"\"Missing Required Interf... | Use Cached Token and Storage URL's rather then grabbing from the Auth System
Example:
<code>
#Create an Auth instance
$auth = new CF_Authentication();
#Pass Cached URL's and Token as Args
$auth->load_cached_credentials("auth_token", "storage_url", "cdn_management_url");
</code>
@param string $auth_token A Cloud Files Auth Token (Required)
@param string $storage_url The Cloud Files Storage URL (Required)
@param string $cdnm_url CDN Management URL (Required)
@return boolean <kbd>True</kbd> if successful
@throws SyntaxException If any of the Required Arguments are missing | [
"Use",
"Cached",
"Token",
"and",
"Storage",
"URL",
"s",
"rather",
"then",
"grabbing",
"from",
"the",
"Auth",
"System"
] | e57a1f23930829cd1c486ef0e3bf7f2bd4fa8563 | https://github.com/guillermomartinez/filemanager-laravel/blob/e57a1f23930829cd1c486ef0e3bf7f2bd4fa8563/src/Pqb/FilemanagerLaravel/plugins/rsc/cloudfiles.php#L242-L257 | train |
guillermomartinez/filemanager-laravel | src/Pqb/FilemanagerLaravel/plugins/rsc/cloudfiles.php | CF_Authentication.export_credentials | function export_credentials()
{
$arr = array();
$arr['storage_url'] = $this->storage_url;
$arr['cdnm_url'] = $this->cdnm_url;
$arr['auth_token'] = $this->auth_token;
return $arr;
} | php | function export_credentials()
{
$arr = array();
$arr['storage_url'] = $this->storage_url;
$arr['cdnm_url'] = $this->cdnm_url;
$arr['auth_token'] = $this->auth_token;
return $arr;
} | [
"function",
"export_credentials",
"(",
")",
"{",
"$",
"arr",
"=",
"array",
"(",
")",
";",
"$",
"arr",
"[",
"'storage_url'",
"]",
"=",
"$",
"this",
"->",
"storage_url",
";",
"$",
"arr",
"[",
"'cdnm_url'",
"]",
"=",
"$",
"this",
"->",
"cdnm_url",
";",
... | Grab Cloud Files info to be Cached for later use with the load_cached_credentials method.
Example:
<code>
#Create an Auth instance
$auth = new CF_Authentication("UserName","API_Key");
$auth->authenticate();
$array = $auth->export_credentials();
</code>
@return array of url's and an auth token. | [
"Grab",
"Cloud",
"Files",
"info",
"to",
"be",
"Cached",
"for",
"later",
"use",
"with",
"the",
"load_cached_credentials",
"method",
"."
] | e57a1f23930829cd1c486ef0e3bf7f2bd4fa8563 | https://github.com/guillermomartinez/filemanager-laravel/blob/e57a1f23930829cd1c486ef0e3bf7f2bd4fa8563/src/Pqb/FilemanagerLaravel/plugins/rsc/cloudfiles.php#L271-L279 | train |
guillermomartinez/filemanager-laravel | src/Pqb/FilemanagerLaravel/plugins/rsc/cloudfiles.php | CF_Connection.create_container | function create_container($container_name=NULL)
{
if ($container_name != "0" and !isset($container_name))
throw new SyntaxException("Container name not set.");
if (!isset($container_name) or $container_name == "")
throw new SyntaxException("Container name not set.");
if (strpos($container_name, "/") !== False) {
$r = "Container name '".$container_name;
$r .= "' cannot contain a '/' character.";
throw new SyntaxException($r);
}
if (strlen($container_name) > MAX_CONTAINER_NAME_LEN) {
throw new SyntaxException(sprintf(
"Container name exeeds %d bytes.",
MAX_CONTAINER_NAME_LEN));
}
$return_code = $this->cfs_http->create_container($container_name);
if (!$return_code) {
throw new InvalidResponseException("Invalid response ("
. $return_code. "): " . $this->cfs_http->get_error());
}
#if ($status == 401 && $this->_re_auth()) {
# return $this->create_container($container_name);
#}
if ($return_code != 201 && $return_code != 202) {
throw new InvalidResponseException(
"Invalid response (".$return_code."): "
. $this->cfs_http->get_error());
}
return new CF_Container($this->cfs_auth, $this->cfs_http, $container_name);
} | php | function create_container($container_name=NULL)
{
if ($container_name != "0" and !isset($container_name))
throw new SyntaxException("Container name not set.");
if (!isset($container_name) or $container_name == "")
throw new SyntaxException("Container name not set.");
if (strpos($container_name, "/") !== False) {
$r = "Container name '".$container_name;
$r .= "' cannot contain a '/' character.";
throw new SyntaxException($r);
}
if (strlen($container_name) > MAX_CONTAINER_NAME_LEN) {
throw new SyntaxException(sprintf(
"Container name exeeds %d bytes.",
MAX_CONTAINER_NAME_LEN));
}
$return_code = $this->cfs_http->create_container($container_name);
if (!$return_code) {
throw new InvalidResponseException("Invalid response ("
. $return_code. "): " . $this->cfs_http->get_error());
}
#if ($status == 401 && $this->_re_auth()) {
# return $this->create_container($container_name);
#}
if ($return_code != 201 && $return_code != 202) {
throw new InvalidResponseException(
"Invalid response (".$return_code."): "
. $this->cfs_http->get_error());
}
return new CF_Container($this->cfs_auth, $this->cfs_http, $container_name);
} | [
"function",
"create_container",
"(",
"$",
"container_name",
"=",
"NULL",
")",
"{",
"if",
"(",
"$",
"container_name",
"!=",
"\"0\"",
"and",
"!",
"isset",
"(",
"$",
"container_name",
")",
")",
"throw",
"new",
"SyntaxException",
"(",
"\"Container name not set.\"",
... | Create a Container
Given a Container name, return a Container instance, creating a new
remote Container if it does not exit.
Example:
<code>
# ... authentication code excluded (see previous examples) ...
#
$conn = new CF_Authentication($auth);
$images = $conn->create_container("my photos");
</code>
@param string $container_name container name
@return CF_Container
@throws SyntaxException invalid name
@throws InvalidResponseException unexpected response | [
"Create",
"a",
"Container"
] | e57a1f23930829cd1c486ef0e3bf7f2bd4fa8563 | https://github.com/guillermomartinez/filemanager-laravel/blob/e57a1f23930829cd1c486ef0e3bf7f2bd4fa8563/src/Pqb/FilemanagerLaravel/plugins/rsc/cloudfiles.php#L476-L509 | train |
guillermomartinez/filemanager-laravel | src/Pqb/FilemanagerLaravel/plugins/rsc/cloudfiles.php | CF_Object._guess_content_type | function _guess_content_type($handle) {
if ($this->content_type)
return true;
if (function_exists("finfo_open")) {
$local_magic = dirname(__FILE__) . "/share/magic";
$finfo = @finfo_open(FILEINFO_MIME, $local_magic);
if (!$finfo)
$finfo = @finfo_open(FILEINFO_MIME);
if ($finfo) {
if (is_file((string)$handle))
$ct = @finfo_file($finfo, $handle);
else
$ct = @finfo_buffer($finfo, $handle);
/* PHP 5.3 fileinfo display extra information like
charset so we remove everything after the ; since
we are not into that stuff */
if ($ct) {
$extra_content_type_info = strpos($ct, "; ");
if ($extra_content_type_info)
$ct = substr($ct, 0, $extra_content_type_info);
}
if ($ct && $ct != 'application/octet-stream')
$this->content_type = $ct;
@finfo_close($finfo);
}
}
if (!$this->content_type && (string)is_file($handle) && function_exists("mime_content_type")) {
$this->content_type = @mime_content_type($handle);
}
if (!$this->content_type) {
throw new BadContentTypeException("Required Content-Type not set");
}
return True;
} | php | function _guess_content_type($handle) {
if ($this->content_type)
return true;
if (function_exists("finfo_open")) {
$local_magic = dirname(__FILE__) . "/share/magic";
$finfo = @finfo_open(FILEINFO_MIME, $local_magic);
if (!$finfo)
$finfo = @finfo_open(FILEINFO_MIME);
if ($finfo) {
if (is_file((string)$handle))
$ct = @finfo_file($finfo, $handle);
else
$ct = @finfo_buffer($finfo, $handle);
/* PHP 5.3 fileinfo display extra information like
charset so we remove everything after the ; since
we are not into that stuff */
if ($ct) {
$extra_content_type_info = strpos($ct, "; ");
if ($extra_content_type_info)
$ct = substr($ct, 0, $extra_content_type_info);
}
if ($ct && $ct != 'application/octet-stream')
$this->content_type = $ct;
@finfo_close($finfo);
}
}
if (!$this->content_type && (string)is_file($handle) && function_exists("mime_content_type")) {
$this->content_type = @mime_content_type($handle);
}
if (!$this->content_type) {
throw new BadContentTypeException("Required Content-Type not set");
}
return True;
} | [
"function",
"_guess_content_type",
"(",
"$",
"handle",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"content_type",
")",
"return",
"true",
";",
"if",
"(",
"function_exists",
"(",
"\"finfo_open\"",
")",
")",
"{",
"$",
"local_magic",
"=",
"dirname",
"(",
"__FILE_... | Internal check to get the proper mimetype.
This function would go over the available PHP methods to get
the MIME type.
By default it will try to use the PHP fileinfo library which is
available from PHP 5.3 or as an PECL extension
(http://pecl.php.net/package/Fileinfo).
It will get the magic file by default from the system wide file
which is usually available in /usr/share/magic on Unix or try
to use the file specified in the source directory of the API
(share directory).
if fileinfo is not available it will try to use the internal
mime_content_type function.
@param string $handle name of file or buffer to guess the type from
@return boolean <kbd>True</kbd> if successful
@throws BadContentTypeException | [
"Internal",
"check",
"to",
"get",
"the",
"proper",
"mimetype",
"."
] | e57a1f23930829cd1c486ef0e3bf7f2bd4fa8563 | https://github.com/guillermomartinez/filemanager-laravel/blob/e57a1f23930829cd1c486ef0e3bf7f2bd4fa8563/src/Pqb/FilemanagerLaravel/plugins/rsc/cloudfiles.php#L1699-L1741 | train |
Payum/PayumLaravelPackage | src/Payum/LaravelPackage/PayumServiceProvider.php | PayumServiceProvider.defineRoutes | protected function defineRoutes()
{
$route = $this->app->make('router');
$route->any('/payment/authorize/{payum_token}', array(
'as' => 'payum_authorize_do',
'uses' => 'Payum\LaravelPackage\Controller\AuthorizeController@doAction'
));
$route->any('/payment/capture/{payum_token}', array(
'as' => 'payum_capture_do',
'uses' => 'Payum\LaravelPackage\Controller\CaptureController@doAction'
));
$route->any('/payment/refund/{payum_token}', array(
'as' => 'payum_refund_do',
'uses' => 'Payum\LaravelPackage\Controller\RefundController@doAction'
));
$route->any('/payment/notify/{payum_token}', array(
'as' => 'payum_notify_do',
'uses' => 'Payum\LaravelPackage\Controller\NotifyController@doAction'
));
$route->any('/payment/notify/unsafe/{gateway_name}', array(
'as' => 'payum_notify_do_unsafe',
'uses' => 'Payum\LaravelPackage\Controller\NotifyController@doUnsafeAction'
));
} | php | protected function defineRoutes()
{
$route = $this->app->make('router');
$route->any('/payment/authorize/{payum_token}', array(
'as' => 'payum_authorize_do',
'uses' => 'Payum\LaravelPackage\Controller\AuthorizeController@doAction'
));
$route->any('/payment/capture/{payum_token}', array(
'as' => 'payum_capture_do',
'uses' => 'Payum\LaravelPackage\Controller\CaptureController@doAction'
));
$route->any('/payment/refund/{payum_token}', array(
'as' => 'payum_refund_do',
'uses' => 'Payum\LaravelPackage\Controller\RefundController@doAction'
));
$route->any('/payment/notify/{payum_token}', array(
'as' => 'payum_notify_do',
'uses' => 'Payum\LaravelPackage\Controller\NotifyController@doAction'
));
$route->any('/payment/notify/unsafe/{gateway_name}', array(
'as' => 'payum_notify_do_unsafe',
'uses' => 'Payum\LaravelPackage\Controller\NotifyController@doUnsafeAction'
));
} | [
"protected",
"function",
"defineRoutes",
"(",
")",
"{",
"$",
"route",
"=",
"$",
"this",
"->",
"app",
"->",
"make",
"(",
"'router'",
")",
";",
"$",
"route",
"->",
"any",
"(",
"'/payment/authorize/{payum_token}'",
",",
"array",
"(",
"'as'",
"=>",
"'payum_aut... | Define all package routes with Laravel router | [
"Define",
"all",
"package",
"routes",
"with",
"Laravel",
"router"
] | 1d02fd53f6df9234b76771c5520aee0f897099db | https://github.com/Payum/PayumLaravelPackage/blob/1d02fd53f6df9234b76771c5520aee0f897099db/src/Payum/LaravelPackage/PayumServiceProvider.php#L108-L136 | train |
guillermomartinez/filemanager-laravel | src/Pqb/FilemanagerLaravel/Filemanager.php | Filemanager.setFileRoot | public function setFileRoot($path) {
if($this->config['options']['serverRoot'] === true) {
$this->doc_root = $_SERVER['DOCUMENT_ROOT']. '/'. $path;
} else {
$this->doc_root = $path;
}
// necessary for retrieving path when set dynamically with $fm->setFileRoot() method
$this->dynamic_fileroot = str_replace($_SERVER['DOCUMENT_ROOT'], '', $this->doc_root);
$this->separator = basename($this->doc_root);
$this->__log(__METHOD__ . ' $this->doc_root value overwritten : ' . $this->doc_root);
$this->__log(__METHOD__ . ' $this->dynamic_fileroot value ' . $this->dynamic_fileroot);
$this->__log(__METHOD__ . ' $this->separator value ' . $this->separator);
} | php | public function setFileRoot($path) {
if($this->config['options']['serverRoot'] === true) {
$this->doc_root = $_SERVER['DOCUMENT_ROOT']. '/'. $path;
} else {
$this->doc_root = $path;
}
// necessary for retrieving path when set dynamically with $fm->setFileRoot() method
$this->dynamic_fileroot = str_replace($_SERVER['DOCUMENT_ROOT'], '', $this->doc_root);
$this->separator = basename($this->doc_root);
$this->__log(__METHOD__ . ' $this->doc_root value overwritten : ' . $this->doc_root);
$this->__log(__METHOD__ . ' $this->dynamic_fileroot value ' . $this->dynamic_fileroot);
$this->__log(__METHOD__ . ' $this->separator value ' . $this->separator);
} | [
"public",
"function",
"setFileRoot",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"config",
"[",
"'options'",
"]",
"[",
"'serverRoot'",
"]",
"===",
"true",
")",
"{",
"$",
"this",
"->",
"doc_root",
"=",
"$",
"_SERVER",
"[",
"'DOCUMENT_ROOT'... | allow Filemanager to be used with dynamic folders | [
"allow",
"Filemanager",
"to",
"be",
"used",
"with",
"dynamic",
"folders"
] | e57a1f23930829cd1c486ef0e3bf7f2bd4fa8563 | https://github.com/guillermomartinez/filemanager-laravel/blob/e57a1f23930829cd1c486ef0e3bf7f2bd4fa8563/src/Pqb/FilemanagerLaravel/Filemanager.php#L89-L101 | train |
guillermomartinez/filemanager-laravel | src/Pqb/FilemanagerLaravel/Filemanager.php | Filemanager.formatPath | private function formatPath($path) {
if($this->dynamic_fileroot != '') {
$a = explode($this->separator, $path);
return end($a);
} else {
return $path;
}
} | php | private function formatPath($path) {
if($this->dynamic_fileroot != '') {
$a = explode($this->separator, $path);
return end($a);
} else {
return $path;
}
} | [
"private",
"function",
"formatPath",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"dynamic_fileroot",
"!=",
"''",
")",
"{",
"$",
"a",
"=",
"explode",
"(",
"$",
"this",
"->",
"separator",
",",
"$",
"path",
")",
";",
"return",
"end",
"("... | format path regarding the initial configuration
@param string $path | [
"format",
"path",
"regarding",
"the",
"initial",
"configuration"
] | e57a1f23930829cd1c486ef0e3bf7f2bd4fa8563 | https://github.com/guillermomartinez/filemanager-laravel/blob/e57a1f23930829cd1c486ef0e3bf7f2bd4fa8563/src/Pqb/FilemanagerLaravel/Filemanager.php#L706-L713 | train |
yii2mod/yii2-google-maps-markers | GoogleMaps.php | GoogleMaps.getGeoCodeData | protected function getGeoCodeData()
{
$result = [];
foreach ($this->userLocations as $data) {
$result[] = [
'country' => ArrayHelper::getValue($data['location'], 'country'),
'address' => implode(',', ArrayHelper::getValue($data, 'location')),
'htmlContent' => ArrayHelper::getValue($data, 'htmlContent'),
];
}
return $result;
} | php | protected function getGeoCodeData()
{
$result = [];
foreach ($this->userLocations as $data) {
$result[] = [
'country' => ArrayHelper::getValue($data['location'], 'country'),
'address' => implode(',', ArrayHelper::getValue($data, 'location')),
'htmlContent' => ArrayHelper::getValue($data, 'htmlContent'),
];
}
return $result;
} | [
"protected",
"function",
"getGeoCodeData",
"(",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"userLocations",
"as",
"$",
"data",
")",
"{",
"$",
"result",
"[",
"]",
"=",
"[",
"'country'",
"=>",
"ArrayHelper",
"::",
"... | Get place urls and htmlContent
@return string | [
"Get",
"place",
"urls",
"and",
"htmlContent"
] | d776b0b176302c4d6cd4ee52044d1a620af29a46 | https://github.com/yii2mod/yii2-google-maps-markers/blob/d776b0b176302c4d6cd4ee52044d1a620af29a46/GoogleMaps.php#L169-L181 | train |
yii2mod/yii2-google-maps-markers | GoogleMaps.php | GoogleMaps.getGoogleMapsUrlOptions | protected function getGoogleMapsUrlOptions()
{
if (isset(Yii::$app->params['googleMapsUrlOptions']) && empty($this->googleMapsUrlOptions)) {
$this->googleMapsUrlOptions = Yii::$app->params['googleMapsUrlOptions'];
}
return ArrayHelper::merge([
'v' => '3.exp',
'key' => null,
'libraries' => null,
'language' => 'en',
], $this->googleMapsUrlOptions);
} | php | protected function getGoogleMapsUrlOptions()
{
if (isset(Yii::$app->params['googleMapsUrlOptions']) && empty($this->googleMapsUrlOptions)) {
$this->googleMapsUrlOptions = Yii::$app->params['googleMapsUrlOptions'];
}
return ArrayHelper::merge([
'v' => '3.exp',
'key' => null,
'libraries' => null,
'language' => 'en',
], $this->googleMapsUrlOptions);
} | [
"protected",
"function",
"getGoogleMapsUrlOptions",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"Yii",
"::",
"$",
"app",
"->",
"params",
"[",
"'googleMapsUrlOptions'",
"]",
")",
"&&",
"empty",
"(",
"$",
"this",
"->",
"googleMapsUrlOptions",
")",
")",
"{",
"$",... | Get google maps url options
@return array | [
"Get",
"google",
"maps",
"url",
"options"
] | d776b0b176302c4d6cd4ee52044d1a620af29a46 | https://github.com/yii2mod/yii2-google-maps-markers/blob/d776b0b176302c4d6cd4ee52044d1a620af29a46/GoogleMaps.php#L198-L210 | train |
yii2mod/yii2-google-maps-markers | GoogleMaps.php | GoogleMaps.getGoogleMapsOptions | protected function getGoogleMapsOptions()
{
if (isset(Yii::$app->params['googleMapsOptions']) && empty($this->googleMapsOptions)) {
$this->googleMapsOptions = Yii::$app->params['googleMapsOptions'];
}
return ArrayHelper::merge([
'mapTypeId' => 'roadmap',
'tilt' => 45,
'zoom' => 2,
], $this->googleMapsOptions);
} | php | protected function getGoogleMapsOptions()
{
if (isset(Yii::$app->params['googleMapsOptions']) && empty($this->googleMapsOptions)) {
$this->googleMapsOptions = Yii::$app->params['googleMapsOptions'];
}
return ArrayHelper::merge([
'mapTypeId' => 'roadmap',
'tilt' => 45,
'zoom' => 2,
], $this->googleMapsOptions);
} | [
"protected",
"function",
"getGoogleMapsOptions",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"Yii",
"::",
"$",
"app",
"->",
"params",
"[",
"'googleMapsOptions'",
"]",
")",
"&&",
"empty",
"(",
"$",
"this",
"->",
"googleMapsOptions",
")",
")",
"{",
"$",
"this"... | Get google maps options
@return array | [
"Get",
"google",
"maps",
"options"
] | d776b0b176302c4d6cd4ee52044d1a620af29a46 | https://github.com/yii2mod/yii2-google-maps-markers/blob/d776b0b176302c4d6cd4ee52044d1a620af29a46/GoogleMaps.php#L217-L228 | train |
yii2mod/yii2-google-maps-markers | GoogleMaps.php | GoogleMaps.getInfoWindowOptions | protected function getInfoWindowOptions()
{
if (isset(Yii::$app->params['infoWindowOptions']) && empty($this->infoWindowOptions)) {
$this->infoWindowOptions = Yii::$app->params['infoWindowOptions'];
}
return ArrayHelper::merge([
'content' => '',
'maxWidth' => 350,
], $this->infoWindowOptions);
} | php | protected function getInfoWindowOptions()
{
if (isset(Yii::$app->params['infoWindowOptions']) && empty($this->infoWindowOptions)) {
$this->infoWindowOptions = Yii::$app->params['infoWindowOptions'];
}
return ArrayHelper::merge([
'content' => '',
'maxWidth' => 350,
], $this->infoWindowOptions);
} | [
"protected",
"function",
"getInfoWindowOptions",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"Yii",
"::",
"$",
"app",
"->",
"params",
"[",
"'infoWindowOptions'",
"]",
")",
"&&",
"empty",
"(",
"$",
"this",
"->",
"infoWindowOptions",
")",
")",
"{",
"$",
"this"... | Get info window options
@return array | [
"Get",
"info",
"window",
"options"
] | d776b0b176302c4d6cd4ee52044d1a620af29a46 | https://github.com/yii2mod/yii2-google-maps-markers/blob/d776b0b176302c4d6cd4ee52044d1a620af29a46/GoogleMaps.php#L235-L245 | train |
yii2mod/yii2-google-maps-markers | GoogleMaps.php | GoogleMaps.getClientOptions | protected function getClientOptions()
{
return Json::encode([
'geocodeData' => $this->geocodeData,
'mapOptions' => $this->googleMapsOptions,
'listeners' => $this->googleMapsListeners,
'containerId' => $this->containerId,
'renderEmptyMap' => $this->renderEmptyMap,
'infoWindowOptions' => $this->infoWindowOptions,
]);
} | php | protected function getClientOptions()
{
return Json::encode([
'geocodeData' => $this->geocodeData,
'mapOptions' => $this->googleMapsOptions,
'listeners' => $this->googleMapsListeners,
'containerId' => $this->containerId,
'renderEmptyMap' => $this->renderEmptyMap,
'infoWindowOptions' => $this->infoWindowOptions,
]);
} | [
"protected",
"function",
"getClientOptions",
"(",
")",
"{",
"return",
"Json",
"::",
"encode",
"(",
"[",
"'geocodeData'",
"=>",
"$",
"this",
"->",
"geocodeData",
",",
"'mapOptions'",
"=>",
"$",
"this",
"->",
"googleMapsOptions",
",",
"'listeners'",
"=>",
"$",
... | Get google map client options
@return string | [
"Get",
"google",
"map",
"client",
"options"
] | d776b0b176302c4d6cd4ee52044d1a620af29a46 | https://github.com/yii2mod/yii2-google-maps-markers/blob/d776b0b176302c4d6cd4ee52044d1a620af29a46/GoogleMaps.php#L252-L262 | train |
splitbrain/php-archive | src/FileInfo.php | FileInfo.fromPath | public static function fromPath($path, $as = '')
{
clearstatcache(false, $path);
if (!file_exists($path)) {
throw new FileInfoException("$path does not exist");
}
$stat = stat($path);
$file = new FileInfo();
$file->setPath($path);
$file->setIsdir(is_dir($path));
$file->setMode(fileperms($path));
$file->setOwner(fileowner($path));
$file->setGroup(filegroup($path));
$file->setSize(filesize($path));
$file->setUid($stat['uid']);
$file->setGid($stat['gid']);
$file->setMtime($stat['mtime']);
if ($as) {
$file->setPath($as);
}
return $file;
} | php | public static function fromPath($path, $as = '')
{
clearstatcache(false, $path);
if (!file_exists($path)) {
throw new FileInfoException("$path does not exist");
}
$stat = stat($path);
$file = new FileInfo();
$file->setPath($path);
$file->setIsdir(is_dir($path));
$file->setMode(fileperms($path));
$file->setOwner(fileowner($path));
$file->setGroup(filegroup($path));
$file->setSize(filesize($path));
$file->setUid($stat['uid']);
$file->setGid($stat['gid']);
$file->setMtime($stat['mtime']);
if ($as) {
$file->setPath($as);
}
return $file;
} | [
"public",
"static",
"function",
"fromPath",
"(",
"$",
"path",
",",
"$",
"as",
"=",
"''",
")",
"{",
"clearstatcache",
"(",
"false",
",",
"$",
"path",
")",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"FileInfo... | Factory to build FileInfo from existing file or directory
@param string $path path to a file on the local file system
@param string $as optional path to use inside the archive
@throws FileInfoException
@return FileInfo | [
"Factory",
"to",
"build",
"FileInfo",
"from",
"existing",
"file",
"or",
"directory"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/FileInfo.php#L48-L74 | train |
splitbrain/php-archive | src/FileInfo.php | FileInfo.cleanPath | protected function cleanPath($path)
{
$path = str_replace('\\', '/', $path);
$path = explode('/', $path);
$newpath = array();
foreach ($path as $p) {
if ($p === '' || $p === '.') {
continue;
}
if ($p === '..') {
array_pop($newpath);
continue;
}
array_push($newpath, $p);
}
return trim(implode('/', $newpath), '/');
} | php | protected function cleanPath($path)
{
$path = str_replace('\\', '/', $path);
$path = explode('/', $path);
$newpath = array();
foreach ($path as $p) {
if ($p === '' || $p === '.') {
continue;
}
if ($p === '..') {
array_pop($newpath);
continue;
}
array_push($newpath, $p);
}
return trim(implode('/', $newpath), '/');
} | [
"protected",
"function",
"cleanPath",
"(",
"$",
"path",
")",
"{",
"$",
"path",
"=",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"$",
"path",
")",
";",
"$",
"path",
"=",
"explode",
"(",
"'/'",
",",
"$",
"path",
")",
";",
"$",
"newpath",
"=",
"a... | Cleans up a path and removes relative parts, also strips leading slashes
@param string $path
@return string | [
"Cleans",
"up",
"a",
"path",
"and",
"removes",
"relative",
"parts",
"also",
"strips",
"leading",
"slashes"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/FileInfo.php#L263-L279 | train |
splitbrain/php-archive | src/FileInfo.php | FileInfo.strip | public function strip($strip)
{
$filename = $this->getPath();
$striplen = strlen($strip);
if (is_int($strip)) {
// if $strip is an integer we strip this many path components
$parts = explode('/', $filename);
if (!$this->getIsdir()) {
$base = array_pop($parts); // keep filename itself
} else {
$base = '';
}
$filename = join('/', array_slice($parts, $strip));
if ($base) {
$filename .= "/$base";
}
} else {
// if strip is a string, we strip a prefix here
if (substr($filename, 0, $striplen) == $strip) {
$filename = substr($filename, $striplen);
}
}
$this->setPath($filename);
} | php | public function strip($strip)
{
$filename = $this->getPath();
$striplen = strlen($strip);
if (is_int($strip)) {
// if $strip is an integer we strip this many path components
$parts = explode('/', $filename);
if (!$this->getIsdir()) {
$base = array_pop($parts); // keep filename itself
} else {
$base = '';
}
$filename = join('/', array_slice($parts, $strip));
if ($base) {
$filename .= "/$base";
}
} else {
// if strip is a string, we strip a prefix here
if (substr($filename, 0, $striplen) == $strip) {
$filename = substr($filename, $striplen);
}
}
$this->setPath($filename);
} | [
"public",
"function",
"strip",
"(",
"$",
"strip",
")",
"{",
"$",
"filename",
"=",
"$",
"this",
"->",
"getPath",
"(",
")",
";",
"$",
"striplen",
"=",
"strlen",
"(",
"$",
"strip",
")",
";",
"if",
"(",
"is_int",
"(",
"$",
"strip",
")",
")",
"{",
"... | Strip given prefix or number of path segments from the filename
The $strip parameter allows you to strip a certain number of path components from the filenames
found in the tar file, similar to the --strip-components feature of GNU tar. This is triggered when
an integer is passed as $strip.
Alternatively a fixed string prefix may be passed in $strip. If the filename matches this prefix,
the prefix will be stripped. It is recommended to give prefixes with a trailing slash.
@param int|string $strip | [
"Strip",
"given",
"prefix",
"or",
"number",
"of",
"path",
"segments",
"from",
"the",
"filename"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/FileInfo.php#L292-L316 | train |
splitbrain/php-archive | src/FileInfo.php | FileInfo.match | public function match($include = '', $exclude = '')
{
$extract = true;
if ($include && !preg_match($include, $this->getPath())) {
$extract = false;
}
if ($exclude && preg_match($exclude, $this->getPath())) {
$extract = false;
}
return $extract;
} | php | public function match($include = '', $exclude = '')
{
$extract = true;
if ($include && !preg_match($include, $this->getPath())) {
$extract = false;
}
if ($exclude && preg_match($exclude, $this->getPath())) {
$extract = false;
}
return $extract;
} | [
"public",
"function",
"match",
"(",
"$",
"include",
"=",
"''",
",",
"$",
"exclude",
"=",
"''",
")",
"{",
"$",
"extract",
"=",
"true",
";",
"if",
"(",
"$",
"include",
"&&",
"!",
"preg_match",
"(",
"$",
"include",
",",
"$",
"this",
"->",
"getPath",
... | Does the file match the given include and exclude expressions?
Exclude rules take precedence over include rules
@param string $include Regular expression of files to include
@param string $exclude Regular expression of files to exclude
@return bool | [
"Does",
"the",
"file",
"match",
"the",
"given",
"include",
"and",
"exclude",
"expressions?"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/FileInfo.php#L327-L338 | train |
splitbrain/php-archive | src/Zip.php | Zip.setCompression | public function setCompression($level = 9, $type = Archive::COMPRESS_AUTO)
{
if ($level < -1 || $level > 9) {
throw new ArchiveIllegalCompressionException('Compression level should be between -1 and 9');
}
$this->complevel = $level;
} | php | public function setCompression($level = 9, $type = Archive::COMPRESS_AUTO)
{
if ($level < -1 || $level > 9) {
throw new ArchiveIllegalCompressionException('Compression level should be between -1 and 9');
}
$this->complevel = $level;
} | [
"public",
"function",
"setCompression",
"(",
"$",
"level",
"=",
"9",
",",
"$",
"type",
"=",
"Archive",
"::",
"COMPRESS_AUTO",
")",
"{",
"if",
"(",
"$",
"level",
"<",
"-",
"1",
"||",
"$",
"level",
">",
"9",
")",
"{",
"throw",
"new",
"ArchiveIllegalCom... | Set the compression level.
Compression Type is ignored for ZIP
You can call this function before adding each file to set differen compression levels
for each file.
@param int $level Compression level (0 to 9)
@param int $type Type of compression to use ignored for ZIP
@throws ArchiveIllegalCompressionException | [
"Set",
"the",
"compression",
"level",
"."
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L39-L45 | train |
splitbrain/php-archive | src/Zip.php | Zip.open | public function open($file)
{
$this->file = $file;
$this->fh = @fopen($this->file, 'rb');
if (!$this->fh) {
throw new ArchiveIOException('Could not open file for reading: '.$this->file);
}
$this->closed = false;
} | php | public function open($file)
{
$this->file = $file;
$this->fh = @fopen($this->file, 'rb');
if (!$this->fh) {
throw new ArchiveIOException('Could not open file for reading: '.$this->file);
}
$this->closed = false;
} | [
"public",
"function",
"open",
"(",
"$",
"file",
")",
"{",
"$",
"this",
"->",
"file",
"=",
"$",
"file",
";",
"$",
"this",
"->",
"fh",
"=",
"@",
"fopen",
"(",
"$",
"this",
"->",
"file",
",",
"'rb'",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
... | Open an existing ZIP file for reading
@param string $file
@throws ArchiveIOException | [
"Open",
"an",
"existing",
"ZIP",
"file",
"for",
"reading"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L53-L61 | train |
splitbrain/php-archive | src/Zip.php | Zip.contents | public function contents()
{
if ($this->closed || !$this->file) {
throw new ArchiveIOException('Can not read from a closed archive');
}
$result = array();
$centd = $this->readCentralDir();
@rewind($this->fh);
@fseek($this->fh, $centd['offset']);
for ($i = 0; $i < $centd['entries']; $i++) {
$result[] = $this->header2fileinfo($this->readCentralFileHeader());
}
$this->close();
return $result;
} | php | public function contents()
{
if ($this->closed || !$this->file) {
throw new ArchiveIOException('Can not read from a closed archive');
}
$result = array();
$centd = $this->readCentralDir();
@rewind($this->fh);
@fseek($this->fh, $centd['offset']);
for ($i = 0; $i < $centd['entries']; $i++) {
$result[] = $this->header2fileinfo($this->readCentralFileHeader());
}
$this->close();
return $result;
} | [
"public",
"function",
"contents",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"closed",
"||",
"!",
"$",
"this",
"->",
"file",
")",
"{",
"throw",
"new",
"ArchiveIOException",
"(",
"'Can not read from a closed archive'",
")",
";",
"}",
"$",
"result",
"=",
... | Read the contents of a ZIP archive
This function lists the files stored in the archive, and returns an indexed array of FileInfo objects
The archive is closed afer reading the contents, for API compatibility with TAR files
Reopen the file with open() again if you want to do additional operations
@throws ArchiveIOException
@return FileInfo[] | [
"Read",
"the",
"contents",
"of",
"a",
"ZIP",
"archive"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L74-L93 | train |
splitbrain/php-archive | src/Zip.php | Zip.create | public function create($file = '')
{
$this->file = $file;
$this->memory = '';
$this->fh = 0;
if ($this->file) {
$this->fh = @fopen($this->file, 'wb');
if (!$this->fh) {
throw new ArchiveIOException('Could not open file for writing: '.$this->file);
}
}
$this->writeaccess = true;
$this->closed = false;
$this->ctrl_dir = array();
} | php | public function create($file = '')
{
$this->file = $file;
$this->memory = '';
$this->fh = 0;
if ($this->file) {
$this->fh = @fopen($this->file, 'wb');
if (!$this->fh) {
throw new ArchiveIOException('Could not open file for writing: '.$this->file);
}
}
$this->writeaccess = true;
$this->closed = false;
$this->ctrl_dir = array();
} | [
"public",
"function",
"create",
"(",
"$",
"file",
"=",
"''",
")",
"{",
"$",
"this",
"->",
"file",
"=",
"$",
"file",
";",
"$",
"this",
"->",
"memory",
"=",
"''",
";",
"$",
"this",
"->",
"fh",
"=",
"0",
";",
"if",
"(",
"$",
"this",
"->",
"file"... | Create a new ZIP file
If $file is empty, the zip file will be created in memory
@param string $file
@throws ArchiveIOException | [
"Create",
"a",
"new",
"ZIP",
"file"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L254-L270 | train |
splitbrain/php-archive | src/Zip.php | Zip.addFile | public function addFile($file, $fileinfo = '')
{
if (is_string($fileinfo)) {
$fileinfo = FileInfo::fromPath($file, $fileinfo);
}
if ($this->closed) {
throw new ArchiveIOException('Archive has been closed, files can no longer be added');
}
$data = @file_get_contents($file);
if ($data === false) {
throw new ArchiveIOException('Could not open file for reading: '.$file);
}
// FIXME could we stream writing compressed data? gzwrite on a fopen handle?
$this->addData($fileinfo, $data);
} | php | public function addFile($file, $fileinfo = '')
{
if (is_string($fileinfo)) {
$fileinfo = FileInfo::fromPath($file, $fileinfo);
}
if ($this->closed) {
throw new ArchiveIOException('Archive has been closed, files can no longer be added');
}
$data = @file_get_contents($file);
if ($data === false) {
throw new ArchiveIOException('Could not open file for reading: '.$file);
}
// FIXME could we stream writing compressed data? gzwrite on a fopen handle?
$this->addData($fileinfo, $data);
} | [
"public",
"function",
"addFile",
"(",
"$",
"file",
",",
"$",
"fileinfo",
"=",
"''",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"fileinfo",
")",
")",
"{",
"$",
"fileinfo",
"=",
"FileInfo",
"::",
"fromPath",
"(",
"$",
"file",
",",
"$",
"fileinfo",
"... | Add a file to the current archive using an existing file in the filesystem
@param string $file path to the original file
@param string|FileInfo $fileinfo either the name to use in archive (string) or a FileInfo oject with all meta data, empty to take from original
@throws ArchiveIOException
@throws FileInfoException | [
"Add",
"a",
"file",
"to",
"the",
"current",
"archive",
"using",
"an",
"existing",
"file",
"in",
"the",
"filesystem"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L288-L305 | train |
splitbrain/php-archive | src/Zip.php | Zip.readCentralDir | protected function readCentralDir()
{
$size = filesize($this->file);
if ($size < 277) {
$maximum_size = $size;
} else {
$maximum_size = 277;
}
@fseek($this->fh, $size - $maximum_size);
$pos = ftell($this->fh);
$bytes = 0x00000000;
while ($pos < $size) {
$byte = @fread($this->fh, 1);
$bytes = (($bytes << 8) & 0xFFFFFFFF) | ord($byte);
if ($bytes == 0x504b0506) {
break;
}
$pos++;
}
$data = unpack(
'vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size',
fread($this->fh, 18)
);
if ($data['comment_size'] != 0) {
$centd['comment'] = fread($this->fh, $data['comment_size']);
} else {
$centd['comment'] = '';
}
$centd['entries'] = $data['entries'];
$centd['disk_entries'] = $data['disk_entries'];
$centd['offset'] = $data['offset'];
$centd['disk_start'] = $data['disk_start'];
$centd['size'] = $data['size'];
$centd['disk'] = $data['disk'];
return $centd;
} | php | protected function readCentralDir()
{
$size = filesize($this->file);
if ($size < 277) {
$maximum_size = $size;
} else {
$maximum_size = 277;
}
@fseek($this->fh, $size - $maximum_size);
$pos = ftell($this->fh);
$bytes = 0x00000000;
while ($pos < $size) {
$byte = @fread($this->fh, 1);
$bytes = (($bytes << 8) & 0xFFFFFFFF) | ord($byte);
if ($bytes == 0x504b0506) {
break;
}
$pos++;
}
$data = unpack(
'vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size',
fread($this->fh, 18)
);
if ($data['comment_size'] != 0) {
$centd['comment'] = fread($this->fh, $data['comment_size']);
} else {
$centd['comment'] = '';
}
$centd['entries'] = $data['entries'];
$centd['disk_entries'] = $data['disk_entries'];
$centd['offset'] = $data['offset'];
$centd['disk_start'] = $data['disk_start'];
$centd['size'] = $data['size'];
$centd['disk'] = $data['disk'];
return $centd;
} | [
"protected",
"function",
"readCentralDir",
"(",
")",
"{",
"$",
"size",
"=",
"filesize",
"(",
"$",
"this",
"->",
"file",
")",
";",
"if",
"(",
"$",
"size",
"<",
"277",
")",
"{",
"$",
"maximum_size",
"=",
"$",
"size",
";",
"}",
"else",
"{",
"$",
"ma... | Read the central directory
This key-value list contains general information about the ZIP file
@return array | [
"Read",
"the",
"central",
"directory"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L450-L489 | train |
splitbrain/php-archive | src/Zip.php | Zip.readCentralFileHeader | protected function readCentralFileHeader()
{
$binary_data = fread($this->fh, 46);
$header = unpack(
'vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset',
$binary_data
);
if ($header['filename_len'] != 0) {
$header['filename'] = fread($this->fh, $header['filename_len']);
} else {
$header['filename'] = '';
}
if ($header['extra_len'] != 0) {
$header['extra'] = fread($this->fh, $header['extra_len']);
$header['extradata'] = $this->parseExtra($header['extra']);
} else {
$header['extra'] = '';
$header['extradata'] = array();
}
if ($header['comment_len'] != 0) {
$header['comment'] = fread($this->fh, $header['comment_len']);
} else {
$header['comment'] = '';
}
$header['mtime'] = $this->makeUnixTime($header['mdate'], $header['mtime']);
$header['stored_filename'] = $header['filename'];
$header['status'] = 'ok';
if (substr($header['filename'], -1) == '/') {
$header['external'] = 0x41FF0010;
}
$header['folder'] = ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0;
return $header;
} | php | protected function readCentralFileHeader()
{
$binary_data = fread($this->fh, 46);
$header = unpack(
'vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset',
$binary_data
);
if ($header['filename_len'] != 0) {
$header['filename'] = fread($this->fh, $header['filename_len']);
} else {
$header['filename'] = '';
}
if ($header['extra_len'] != 0) {
$header['extra'] = fread($this->fh, $header['extra_len']);
$header['extradata'] = $this->parseExtra($header['extra']);
} else {
$header['extra'] = '';
$header['extradata'] = array();
}
if ($header['comment_len'] != 0) {
$header['comment'] = fread($this->fh, $header['comment_len']);
} else {
$header['comment'] = '';
}
$header['mtime'] = $this->makeUnixTime($header['mdate'], $header['mtime']);
$header['stored_filename'] = $header['filename'];
$header['status'] = 'ok';
if (substr($header['filename'], -1) == '/') {
$header['external'] = 0x41FF0010;
}
$header['folder'] = ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0;
return $header;
} | [
"protected",
"function",
"readCentralFileHeader",
"(",
")",
"{",
"$",
"binary_data",
"=",
"fread",
"(",
"$",
"this",
"->",
"fh",
",",
"46",
")",
";",
"$",
"header",
"=",
"unpack",
"(",
"'vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcom... | Read the next central file header
Assumes the current file pointer is pointing at the right position
@return array | [
"Read",
"the",
"next",
"central",
"file",
"header"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L498-L535 | train |
splitbrain/php-archive | src/Zip.php | Zip.readFileHeader | protected function readFileHeader($header)
{
$binary_data = fread($this->fh, 30);
$data = unpack(
'vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len',
$binary_data
);
$header['filename'] = fread($this->fh, $data['filename_len']);
if ($data['extra_len'] != 0) {
$header['extra'] = fread($this->fh, $data['extra_len']);
$header['extradata'] = array_merge($header['extradata'], $this->parseExtra($header['extra']));
} else {
$header['extra'] = '';
$header['extradata'] = array();
}
$header['compression'] = $data['compression'];
foreach (array(
'size',
'compressed_size',
'crc'
) as $hd) { // On ODT files, these headers are 0. Keep the previous value.
if ($data[$hd] != 0) {
$header[$hd] = $data[$hd];
}
}
$header['flag'] = $data['flag'];
$header['mtime'] = $this->makeUnixTime($data['mdate'], $data['mtime']);
$header['stored_filename'] = $header['filename'];
$header['status'] = "ok";
$header['folder'] = ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0;
return $header;
} | php | protected function readFileHeader($header)
{
$binary_data = fread($this->fh, 30);
$data = unpack(
'vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len',
$binary_data
);
$header['filename'] = fread($this->fh, $data['filename_len']);
if ($data['extra_len'] != 0) {
$header['extra'] = fread($this->fh, $data['extra_len']);
$header['extradata'] = array_merge($header['extradata'], $this->parseExtra($header['extra']));
} else {
$header['extra'] = '';
$header['extradata'] = array();
}
$header['compression'] = $data['compression'];
foreach (array(
'size',
'compressed_size',
'crc'
) as $hd) { // On ODT files, these headers are 0. Keep the previous value.
if ($data[$hd] != 0) {
$header[$hd] = $data[$hd];
}
}
$header['flag'] = $data['flag'];
$header['mtime'] = $this->makeUnixTime($data['mdate'], $data['mtime']);
$header['stored_filename'] = $header['filename'];
$header['status'] = "ok";
$header['folder'] = ($header['external'] == 0x41FF0010 || $header['external'] == 16) ? 1 : 0;
return $header;
} | [
"protected",
"function",
"readFileHeader",
"(",
"$",
"header",
")",
"{",
"$",
"binary_data",
"=",
"fread",
"(",
"$",
"this",
"->",
"fh",
",",
"30",
")",
";",
"$",
"data",
"=",
"unpack",
"(",
"'vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_siz... | Reads the local file header
This header precedes each individual file inside the zip file. Assumes the current file pointer is pointing at
the right position already. Enhances the given central header with the data found at the local header.
@param array $header the central file header read previously (see above)
@return array | [
"Reads",
"the",
"local",
"file",
"header"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L546-L580 | train |
splitbrain/php-archive | src/Zip.php | Zip.parseExtra | protected function parseExtra($header)
{
$extra = array();
// parse all extra fields as raw values
while (strlen($header) !== 0) {
$set = unpack('vid/vlen', $header);
$header = substr($header, 4);
$value = substr($header, 0, $set['len']);
$header = substr($header, $set['len']);
$extra[$set['id']] = $value;
}
// handle known ones
if(isset($extra[0x6375])) {
$extra['utf8comment'] = substr($extra[0x7075], 5); // strip version and crc
}
if(isset($extra[0x7075])) {
$extra['utf8path'] = substr($extra[0x7075], 5); // strip version and crc
}
return $extra;
} | php | protected function parseExtra($header)
{
$extra = array();
// parse all extra fields as raw values
while (strlen($header) !== 0) {
$set = unpack('vid/vlen', $header);
$header = substr($header, 4);
$value = substr($header, 0, $set['len']);
$header = substr($header, $set['len']);
$extra[$set['id']] = $value;
}
// handle known ones
if(isset($extra[0x6375])) {
$extra['utf8comment'] = substr($extra[0x7075], 5); // strip version and crc
}
if(isset($extra[0x7075])) {
$extra['utf8path'] = substr($extra[0x7075], 5); // strip version and crc
}
return $extra;
} | [
"protected",
"function",
"parseExtra",
"(",
"$",
"header",
")",
"{",
"$",
"extra",
"=",
"array",
"(",
")",
";",
"// parse all extra fields as raw values",
"while",
"(",
"strlen",
"(",
"$",
"header",
")",
"!==",
"0",
")",
"{",
"$",
"set",
"=",
"unpack",
"... | Parse the extra headers into fields
@param string $header
@return array | [
"Parse",
"the",
"extra",
"headers",
"into",
"fields"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L588-L609 | train |
splitbrain/php-archive | src/Zip.php | Zip.header2fileinfo | protected function header2fileinfo($header)
{
$fileinfo = new FileInfo();
$fileinfo->setSize($header['size']);
$fileinfo->setCompressedSize($header['compressed_size']);
$fileinfo->setMtime($header['mtime']);
$fileinfo->setComment($header['comment']);
$fileinfo->setIsdir($header['external'] == 0x41FF0010 || $header['external'] == 16);
if(isset($header['extradata']['utf8path'])) {
$fileinfo->setPath($header['extradata']['utf8path']);
} else {
$fileinfo->setPath($this->cpToUtf8($header['filename']));
}
if(isset($header['extradata']['utf8comment'])) {
$fileinfo->setComment($header['extradata']['utf8comment']);
} else {
$fileinfo->setComment($this->cpToUtf8($header['comment']));
}
return $fileinfo;
} | php | protected function header2fileinfo($header)
{
$fileinfo = new FileInfo();
$fileinfo->setSize($header['size']);
$fileinfo->setCompressedSize($header['compressed_size']);
$fileinfo->setMtime($header['mtime']);
$fileinfo->setComment($header['comment']);
$fileinfo->setIsdir($header['external'] == 0x41FF0010 || $header['external'] == 16);
if(isset($header['extradata']['utf8path'])) {
$fileinfo->setPath($header['extradata']['utf8path']);
} else {
$fileinfo->setPath($this->cpToUtf8($header['filename']));
}
if(isset($header['extradata']['utf8comment'])) {
$fileinfo->setComment($header['extradata']['utf8comment']);
} else {
$fileinfo->setComment($this->cpToUtf8($header['comment']));
}
return $fileinfo;
} | [
"protected",
"function",
"header2fileinfo",
"(",
"$",
"header",
")",
"{",
"$",
"fileinfo",
"=",
"new",
"FileInfo",
"(",
")",
";",
"$",
"fileinfo",
"->",
"setSize",
"(",
"$",
"header",
"[",
"'size'",
"]",
")",
";",
"$",
"fileinfo",
"->",
"setCompressedSiz... | Create fileinfo object from header data
@param $header
@return FileInfo | [
"Create",
"fileinfo",
"object",
"from",
"header",
"data"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L617-L639 | train |
splitbrain/php-archive | src/Zip.php | Zip.cpToUtf8 | protected function cpToUtf8($string)
{
if (function_exists('iconv') && @iconv_strlen('', 'CP437') !== false) {
return iconv('CP437', 'UTF-8', $string);
} elseif (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($string, 'UTF-8', 'CP850');
} else {
return $string;
}
} | php | protected function cpToUtf8($string)
{
if (function_exists('iconv') && @iconv_strlen('', 'CP437') !== false) {
return iconv('CP437', 'UTF-8', $string);
} elseif (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($string, 'UTF-8', 'CP850');
} else {
return $string;
}
} | [
"protected",
"function",
"cpToUtf8",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'iconv'",
")",
"&&",
"@",
"iconv_strlen",
"(",
"''",
",",
"'CP437'",
")",
"!==",
"false",
")",
"{",
"return",
"iconv",
"(",
"'CP437'",
",",
"'UTF-8'",
... | Convert the given CP437 encoded string to UTF-8
Tries iconv with the correct encoding first, falls back to mbstring with CP850 which is
similar enough. CP437 seems not to be available in mbstring. Lastly falls back to keeping the
string as is, which is still better than nothing.
On some systems iconv is available, but the codepage is not. We also check for that.
@param $string
@return string | [
"Convert",
"the",
"given",
"CP437",
"encoded",
"string",
"to",
"UTF",
"-",
"8"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L653-L662 | train |
splitbrain/php-archive | src/Zip.php | Zip.utf8ToCp | protected function utf8ToCp($string)
{
// try iconv first
if (function_exists('iconv')) {
$conv = @iconv('UTF-8', 'CP437//IGNORE', $string);
if($conv) return $conv; // it worked
}
// still here? iconv failed to convert the string. Try another method
// see http://php.net/manual/en/function.iconv.php#108643
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($string, 'CP850', 'UTF-8');
} else {
return $string;
}
} | php | protected function utf8ToCp($string)
{
// try iconv first
if (function_exists('iconv')) {
$conv = @iconv('UTF-8', 'CP437//IGNORE', $string);
if($conv) return $conv; // it worked
}
// still here? iconv failed to convert the string. Try another method
// see http://php.net/manual/en/function.iconv.php#108643
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($string, 'CP850', 'UTF-8');
} else {
return $string;
}
} | [
"protected",
"function",
"utf8ToCp",
"(",
"$",
"string",
")",
"{",
"// try iconv first",
"if",
"(",
"function_exists",
"(",
"'iconv'",
")",
")",
"{",
"$",
"conv",
"=",
"@",
"iconv",
"(",
"'UTF-8'",
",",
"'CP437//IGNORE'",
",",
"$",
"string",
")",
";",
"i... | Convert the given UTF-8 encoded string to CP437
Same caveats as for cpToUtf8() apply
@param $string
@return string | [
"Convert",
"the",
"given",
"UTF",
"-",
"8",
"encoded",
"string",
"to",
"CP437"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L672-L688 | train |
splitbrain/php-archive | src/Zip.php | Zip.makeDosTime | protected function makeDosTime($time)
{
$timearray = getdate($time);
if ($timearray['year'] < 1980) {
$timearray['year'] = 1980;
$timearray['mon'] = 1;
$timearray['mday'] = 1;
$timearray['hours'] = 0;
$timearray['minutes'] = 0;
$timearray['seconds'] = 0;
}
return (($timearray['year'] - 1980) << 25) |
($timearray['mon'] << 21) |
($timearray['mday'] << 16) |
($timearray['hours'] << 11) |
($timearray['minutes'] << 5) |
($timearray['seconds'] >> 1);
} | php | protected function makeDosTime($time)
{
$timearray = getdate($time);
if ($timearray['year'] < 1980) {
$timearray['year'] = 1980;
$timearray['mon'] = 1;
$timearray['mday'] = 1;
$timearray['hours'] = 0;
$timearray['minutes'] = 0;
$timearray['seconds'] = 0;
}
return (($timearray['year'] - 1980) << 25) |
($timearray['mon'] << 21) |
($timearray['mday'] << 16) |
($timearray['hours'] << 11) |
($timearray['minutes'] << 5) |
($timearray['seconds'] >> 1);
} | [
"protected",
"function",
"makeDosTime",
"(",
"$",
"time",
")",
"{",
"$",
"timearray",
"=",
"getdate",
"(",
"$",
"time",
")",
";",
"if",
"(",
"$",
"timearray",
"[",
"'year'",
"]",
"<",
"1980",
")",
"{",
"$",
"timearray",
"[",
"'year'",
"]",
"=",
"19... | Create a DOS timestamp from a UNIX timestamp
DOS timestamps start at 1980-01-01, earlier UNIX stamps will be set to this date
@param $time
@return int | [
"Create",
"a",
"DOS",
"timestamp",
"from",
"a",
"UNIX",
"timestamp"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L735-L752 | train |
splitbrain/php-archive | src/Zip.php | Zip.makeUnixTime | protected function makeUnixTime($mdate = null, $mtime = null)
{
if ($mdate && $mtime) {
$year = (($mdate & 0xFE00) >> 9) + 1980;
$month = ($mdate & 0x01E0) >> 5;
$day = $mdate & 0x001F;
$hour = ($mtime & 0xF800) >> 11;
$minute = ($mtime & 0x07E0) >> 5;
$seconde = ($mtime & 0x001F) << 1;
$mtime = mktime($hour, $minute, $seconde, $month, $day, $year);
} else {
$mtime = time();
}
return $mtime;
} | php | protected function makeUnixTime($mdate = null, $mtime = null)
{
if ($mdate && $mtime) {
$year = (($mdate & 0xFE00) >> 9) + 1980;
$month = ($mdate & 0x01E0) >> 5;
$day = $mdate & 0x001F;
$hour = ($mtime & 0xF800) >> 11;
$minute = ($mtime & 0x07E0) >> 5;
$seconde = ($mtime & 0x001F) << 1;
$mtime = mktime($hour, $minute, $seconde, $month, $day, $year);
} else {
$mtime = time();
}
return $mtime;
} | [
"protected",
"function",
"makeUnixTime",
"(",
"$",
"mdate",
"=",
"null",
",",
"$",
"mtime",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"mdate",
"&&",
"$",
"mtime",
")",
"{",
"$",
"year",
"=",
"(",
"(",
"$",
"mdate",
"&",
"0xFE00",
")",
">>",
"9",
"... | Create a UNIX timestamp from a DOS timestamp
@param $mdate
@param $mtime
@return int | [
"Create",
"a",
"UNIX",
"timestamp",
"from",
"a",
"DOS",
"timestamp"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L761-L778 | train |
splitbrain/php-archive | src/Zip.php | Zip.makeCentralFileRecord | protected function makeCentralFileRecord($offset, $ts, $crc, $len, $clen, $name, $comp = null)
{
if(is_null($comp)) $comp = $len != $clen;
$comp = $comp ? 8 : 0;
$dtime = dechex($this->makeDosTime($ts));
list($name, $extra) = $this->encodeFilename($name);
$header = "\x50\x4b\x01\x02"; // central file header signature
$header .= pack('v', 14); // version made by - VFAT
$header .= pack('v', 20); // version needed to extract - 2.0
$header .= pack('v', 0); // general purpose flag - no flags set
$header .= pack('v', $comp); // compression method - deflate|none
$header .= pack(
'H*',
$dtime[6] . $dtime[7] .
$dtime[4] . $dtime[5] .
$dtime[2] . $dtime[3] .
$dtime[0] . $dtime[1]
); // last mod file time and date
$header .= pack('V', $crc); // crc-32
$header .= pack('V', $clen); // compressed size
$header .= pack('V', $len); // uncompressed size
$header .= pack('v', strlen($name)); // file name length
$header .= pack('v', strlen($extra)); // extra field length
$header .= pack('v', 0); // file comment length
$header .= pack('v', 0); // disk number start
$header .= pack('v', 0); // internal file attributes
$header .= pack('V', 0); // external file attributes @todo was 0x32!?
$header .= pack('V', $offset); // relative offset of local header
$header .= $name; // file name
$header .= $extra; // extra (utf-8 filename)
return $header;
} | php | protected function makeCentralFileRecord($offset, $ts, $crc, $len, $clen, $name, $comp = null)
{
if(is_null($comp)) $comp = $len != $clen;
$comp = $comp ? 8 : 0;
$dtime = dechex($this->makeDosTime($ts));
list($name, $extra) = $this->encodeFilename($name);
$header = "\x50\x4b\x01\x02"; // central file header signature
$header .= pack('v', 14); // version made by - VFAT
$header .= pack('v', 20); // version needed to extract - 2.0
$header .= pack('v', 0); // general purpose flag - no flags set
$header .= pack('v', $comp); // compression method - deflate|none
$header .= pack(
'H*',
$dtime[6] . $dtime[7] .
$dtime[4] . $dtime[5] .
$dtime[2] . $dtime[3] .
$dtime[0] . $dtime[1]
); // last mod file time and date
$header .= pack('V', $crc); // crc-32
$header .= pack('V', $clen); // compressed size
$header .= pack('V', $len); // uncompressed size
$header .= pack('v', strlen($name)); // file name length
$header .= pack('v', strlen($extra)); // extra field length
$header .= pack('v', 0); // file comment length
$header .= pack('v', 0); // disk number start
$header .= pack('v', 0); // internal file attributes
$header .= pack('V', 0); // external file attributes @todo was 0x32!?
$header .= pack('V', $offset); // relative offset of local header
$header .= $name; // file name
$header .= $extra; // extra (utf-8 filename)
return $header;
} | [
"protected",
"function",
"makeCentralFileRecord",
"(",
"$",
"offset",
",",
"$",
"ts",
",",
"$",
"crc",
",",
"$",
"len",
",",
"$",
"clen",
",",
"$",
"name",
",",
"$",
"comp",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"comp",
")",
")",... | Returns a local file header for the given data
@param int $offset location of the local header
@param int $ts unix timestamp
@param int $crc CRC32 checksum of the uncompressed data
@param int $len length of the uncompressed data
@param int $clen length of the compressed data
@param string $name file name
@param boolean|null $comp if compression is used, if null it's determined from $len != $clen
@return string | [
"Returns",
"a",
"local",
"file",
"header",
"for",
"the",
"given",
"data"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L792-L826 | train |
splitbrain/php-archive | src/Zip.php | Zip.encodeFilename | protected function encodeFilename($original)
{
$cp437 = $this->utf8ToCp($original);
if ($cp437 === $original) {
return array($original, '');
}
$extra = pack(
'vvCV',
0x7075, // tag
strlen($original) + 5, // length of file + version + crc
1, // version
crc32($original) // crc
);
$extra .= $original;
return array($cp437, $extra);
} | php | protected function encodeFilename($original)
{
$cp437 = $this->utf8ToCp($original);
if ($cp437 === $original) {
return array($original, '');
}
$extra = pack(
'vvCV',
0x7075, // tag
strlen($original) + 5, // length of file + version + crc
1, // version
crc32($original) // crc
);
$extra .= $original;
return array($cp437, $extra);
} | [
"protected",
"function",
"encodeFilename",
"(",
"$",
"original",
")",
"{",
"$",
"cp437",
"=",
"$",
"this",
"->",
"utf8ToCp",
"(",
"$",
"original",
")",
";",
"if",
"(",
"$",
"cp437",
"===",
"$",
"original",
")",
"{",
"return",
"array",
"(",
"$",
"orig... | Returns an allowed filename and an extra field header
When encoding stuff outside the 7bit ASCII range it needs to be placed in a separate
extra field
@param $original
@return array($filename, $extra) | [
"Returns",
"an",
"allowed",
"filename",
"and",
"an",
"extra",
"field",
"header"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Zip.php#L877-L894 | train |
splitbrain/php-archive | src/Tar.php | Tar.setCompression | public function setCompression($level = 9, $type = Archive::COMPRESS_AUTO)
{
$this->compressioncheck($type);
if ($level < -1 || $level > 9) {
throw new ArchiveIllegalCompressionException('Compression level should be between -1 and 9');
}
$this->comptype = $type;
$this->complevel = $level;
if($level == 0) $this->comptype = Archive::COMPRESS_NONE;
if($type == Archive::COMPRESS_NONE) $this->complevel = 0;
} | php | public function setCompression($level = 9, $type = Archive::COMPRESS_AUTO)
{
$this->compressioncheck($type);
if ($level < -1 || $level > 9) {
throw new ArchiveIllegalCompressionException('Compression level should be between -1 and 9');
}
$this->comptype = $type;
$this->complevel = $level;
if($level == 0) $this->comptype = Archive::COMPRESS_NONE;
if($type == Archive::COMPRESS_NONE) $this->complevel = 0;
} | [
"public",
"function",
"setCompression",
"(",
"$",
"level",
"=",
"9",
",",
"$",
"type",
"=",
"Archive",
"::",
"COMPRESS_AUTO",
")",
"{",
"$",
"this",
"->",
"compressioncheck",
"(",
"$",
"type",
")",
";",
"if",
"(",
"$",
"level",
"<",
"-",
"1",
"||",
... | Sets the compression to use
@param int $level Compression level (0 to 9)
@param int $type Type of compression to use (use COMPRESS_* constants)
@throws ArchiveIllegalCompressionException | [
"Sets",
"the",
"compression",
"to",
"use"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Tar.php#L34-L44 | train |
splitbrain/php-archive | src/Tar.php | Tar.open | public function open($file)
{
$this->file = $file;
// update compression to mach file
if ($this->comptype == Tar::COMPRESS_AUTO) {
$this->setCompression($this->complevel, $this->filetype($file));
}
// open file handles
if ($this->comptype === Archive::COMPRESS_GZIP) {
$this->fh = @gzopen($this->file, 'rb');
} elseif ($this->comptype === Archive::COMPRESS_BZIP) {
$this->fh = @bzopen($this->file, 'r');
} else {
$this->fh = @fopen($this->file, 'rb');
}
if (!$this->fh) {
throw new ArchiveIOException('Could not open file for reading: '.$this->file);
}
$this->closed = false;
} | php | public function open($file)
{
$this->file = $file;
// update compression to mach file
if ($this->comptype == Tar::COMPRESS_AUTO) {
$this->setCompression($this->complevel, $this->filetype($file));
}
// open file handles
if ($this->comptype === Archive::COMPRESS_GZIP) {
$this->fh = @gzopen($this->file, 'rb');
} elseif ($this->comptype === Archive::COMPRESS_BZIP) {
$this->fh = @bzopen($this->file, 'r');
} else {
$this->fh = @fopen($this->file, 'rb');
}
if (!$this->fh) {
throw new ArchiveIOException('Could not open file for reading: '.$this->file);
}
$this->closed = false;
} | [
"public",
"function",
"open",
"(",
"$",
"file",
")",
"{",
"$",
"this",
"->",
"file",
"=",
"$",
"file",
";",
"// update compression to mach file",
"if",
"(",
"$",
"this",
"->",
"comptype",
"==",
"Tar",
"::",
"COMPRESS_AUTO",
")",
"{",
"$",
"this",
"->",
... | Open an existing TAR file for reading
@param string $file
@throws ArchiveIOException
@throws ArchiveIllegalCompressionException | [
"Open",
"an",
"existing",
"TAR",
"file",
"for",
"reading"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Tar.php#L53-L75 | train |
splitbrain/php-archive | src/Tar.php | Tar.contents | public function contents()
{
if ($this->closed || !$this->file) {
throw new ArchiveIOException('Can not read from a closed archive');
}
$result = array();
while ($read = $this->readbytes(512)) {
$header = $this->parseHeader($read);
if (!is_array($header)) {
continue;
}
$this->skipbytes(ceil($header['size'] / 512) * 512);
$result[] = $this->header2fileinfo($header);
}
$this->close();
return $result;
} | php | public function contents()
{
if ($this->closed || !$this->file) {
throw new ArchiveIOException('Can not read from a closed archive');
}
$result = array();
while ($read = $this->readbytes(512)) {
$header = $this->parseHeader($read);
if (!is_array($header)) {
continue;
}
$this->skipbytes(ceil($header['size'] / 512) * 512);
$result[] = $this->header2fileinfo($header);
}
$this->close();
return $result;
} | [
"public",
"function",
"contents",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"closed",
"||",
"!",
"$",
"this",
"->",
"file",
")",
"{",
"throw",
"new",
"ArchiveIOException",
"(",
"'Can not read from a closed archive'",
")",
";",
"}",
"$",
"result",
"=",
... | Read the contents of a TAR archive
This function lists the files stored in the archive
The archive is closed afer reading the contents, because rewinding is not possible in bzip2 streams.
Reopen the file with open() again if you want to do additional operations
@throws ArchiveIOException
@throws ArchiveCorruptedException
@returns FileInfo[] | [
"Read",
"the",
"contents",
"of",
"a",
"TAR",
"archive"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Tar.php#L89-L108 | train |
splitbrain/php-archive | src/Tar.php | Tar.extract | public function extract($outdir, $strip = '', $exclude = '', $include = '')
{
if ($this->closed || !$this->file) {
throw new ArchiveIOException('Can not read from a closed archive');
}
$outdir = rtrim($outdir, '/');
@mkdir($outdir, 0777, true);
if (!is_dir($outdir)) {
throw new ArchiveIOException("Could not create directory '$outdir'");
}
$extracted = array();
while ($dat = $this->readbytes(512)) {
// read the file header
$header = $this->parseHeader($dat);
if (!is_array($header)) {
continue;
}
$fileinfo = $this->header2fileinfo($header);
// apply strip rules
$fileinfo->strip($strip);
// skip unwanted files
if (!strlen($fileinfo->getPath()) || !$fileinfo->match($include, $exclude)) {
$this->skipbytes(ceil($header['size'] / 512) * 512);
continue;
}
// create output directory
$output = $outdir.'/'.$fileinfo->getPath();
$directory = ($fileinfo->getIsdir()) ? $output : dirname($output);
@mkdir($directory, 0777, true);
// extract data
if (!$fileinfo->getIsdir()) {
$fp = @fopen($output, "wb");
if (!$fp) {
throw new ArchiveIOException('Could not open file for writing: '.$output);
}
$size = floor($header['size'] / 512);
for ($i = 0; $i < $size; $i++) {
fwrite($fp, $this->readbytes(512), 512);
}
if (($header['size'] % 512) != 0) {
fwrite($fp, $this->readbytes(512), $header['size'] % 512);
}
fclose($fp);
@touch($output, $fileinfo->getMtime());
@chmod($output, $fileinfo->getMode());
} else {
$this->skipbytes(ceil($header['size'] / 512) * 512); // the size is usually 0 for directories
}
if(is_callable($this->callback)) {
call_user_func($this->callback, $fileinfo);
}
$extracted[] = $fileinfo;
}
$this->close();
return $extracted;
} | php | public function extract($outdir, $strip = '', $exclude = '', $include = '')
{
if ($this->closed || !$this->file) {
throw new ArchiveIOException('Can not read from a closed archive');
}
$outdir = rtrim($outdir, '/');
@mkdir($outdir, 0777, true);
if (!is_dir($outdir)) {
throw new ArchiveIOException("Could not create directory '$outdir'");
}
$extracted = array();
while ($dat = $this->readbytes(512)) {
// read the file header
$header = $this->parseHeader($dat);
if (!is_array($header)) {
continue;
}
$fileinfo = $this->header2fileinfo($header);
// apply strip rules
$fileinfo->strip($strip);
// skip unwanted files
if (!strlen($fileinfo->getPath()) || !$fileinfo->match($include, $exclude)) {
$this->skipbytes(ceil($header['size'] / 512) * 512);
continue;
}
// create output directory
$output = $outdir.'/'.$fileinfo->getPath();
$directory = ($fileinfo->getIsdir()) ? $output : dirname($output);
@mkdir($directory, 0777, true);
// extract data
if (!$fileinfo->getIsdir()) {
$fp = @fopen($output, "wb");
if (!$fp) {
throw new ArchiveIOException('Could not open file for writing: '.$output);
}
$size = floor($header['size'] / 512);
for ($i = 0; $i < $size; $i++) {
fwrite($fp, $this->readbytes(512), 512);
}
if (($header['size'] % 512) != 0) {
fwrite($fp, $this->readbytes(512), $header['size'] % 512);
}
fclose($fp);
@touch($output, $fileinfo->getMtime());
@chmod($output, $fileinfo->getMode());
} else {
$this->skipbytes(ceil($header['size'] / 512) * 512); // the size is usually 0 for directories
}
if(is_callable($this->callback)) {
call_user_func($this->callback, $fileinfo);
}
$extracted[] = $fileinfo;
}
$this->close();
return $extracted;
} | [
"public",
"function",
"extract",
"(",
"$",
"outdir",
",",
"$",
"strip",
"=",
"''",
",",
"$",
"exclude",
"=",
"''",
",",
"$",
"include",
"=",
"''",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"closed",
"||",
"!",
"$",
"this",
"->",
"file",
")",
"{",... | Extract an existing TAR archive
The $strip parameter allows you to strip a certain number of path components from the filenames
found in the tar file, similar to the --strip-components feature of GNU tar. This is triggered when
an integer is passed as $strip.
Alternatively a fixed string prefix may be passed in $strip. If the filename matches this prefix,
the prefix will be stripped. It is recommended to give prefixes with a trailing slash.
By default this will extract all files found in the archive. You can restrict the output using the $include
and $exclude parameter. Both expect a full regular expression (including delimiters and modifiers). If
$include is set only files that match this expression will be extracted. Files that match the $exclude
expression will never be extracted. Both parameters can be used in combination. Expressions are matched against
stripped filenames as described above.
The archive is closed afer reading the contents, because rewinding is not possible in bzip2 streams.
Reopen the file with open() again if you want to do additional operations
@param string $outdir the target directory for extracting
@param int|string $strip either the number of path components or a fixed prefix to strip
@param string $exclude a regular expression of files to exclude
@param string $include a regular expression of files to include
@throws ArchiveIOException
@throws ArchiveCorruptedException
@return FileInfo[] | [
"Extract",
"an",
"existing",
"TAR",
"archive"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Tar.php#L136-L201 | train |
splitbrain/php-archive | src/Tar.php | Tar.create | public function create($file = '')
{
$this->file = $file;
$this->memory = '';
$this->fh = 0;
if ($this->file) {
// determine compression
if ($this->comptype == Archive::COMPRESS_AUTO) {
$this->setCompression($this->complevel, $this->filetype($file));
}
if ($this->comptype === Archive::COMPRESS_GZIP) {
$this->fh = @gzopen($this->file, 'wb'.$this->complevel);
} elseif ($this->comptype === Archive::COMPRESS_BZIP) {
$this->fh = @bzopen($this->file, 'w');
} else {
$this->fh = @fopen($this->file, 'wb');
}
if (!$this->fh) {
throw new ArchiveIOException('Could not open file for writing: '.$this->file);
}
}
$this->writeaccess = true;
$this->closed = false;
} | php | public function create($file = '')
{
$this->file = $file;
$this->memory = '';
$this->fh = 0;
if ($this->file) {
// determine compression
if ($this->comptype == Archive::COMPRESS_AUTO) {
$this->setCompression($this->complevel, $this->filetype($file));
}
if ($this->comptype === Archive::COMPRESS_GZIP) {
$this->fh = @gzopen($this->file, 'wb'.$this->complevel);
} elseif ($this->comptype === Archive::COMPRESS_BZIP) {
$this->fh = @bzopen($this->file, 'w');
} else {
$this->fh = @fopen($this->file, 'wb');
}
if (!$this->fh) {
throw new ArchiveIOException('Could not open file for writing: '.$this->file);
}
}
$this->writeaccess = true;
$this->closed = false;
} | [
"public",
"function",
"create",
"(",
"$",
"file",
"=",
"''",
")",
"{",
"$",
"this",
"->",
"file",
"=",
"$",
"file",
";",
"$",
"this",
"->",
"memory",
"=",
"''",
";",
"$",
"this",
"->",
"fh",
"=",
"0",
";",
"if",
"(",
"$",
"this",
"->",
"file"... | Create a new TAR file
If $file is empty, the tar file will be created in memory
@param string $file
@throws ArchiveIOException
@throws ArchiveIllegalCompressionException | [
"Create",
"a",
"new",
"TAR",
"file"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Tar.php#L212-L238 | train |
splitbrain/php-archive | src/Tar.php | Tar.addFile | public function addFile($file, $fileinfo = '')
{
if (is_string($fileinfo)) {
$fileinfo = FileInfo::fromPath($file, $fileinfo);
}
if ($this->closed) {
throw new ArchiveIOException('Archive has been closed, files can no longer be added');
}
$fp = @fopen($file, 'rb');
if (!$fp) {
throw new ArchiveIOException('Could not open file for reading: '.$file);
}
// create file header
$this->writeFileHeader($fileinfo);
// write data
$read = 0;
while (!feof($fp)) {
$data = fread($fp, 512);
$read += strlen($data);
if ($data === false) {
break;
}
if ($data === '') {
break;
}
$packed = pack("a512", $data);
$this->writebytes($packed);
}
fclose($fp);
if($read != $fileinfo->getSize()) {
$this->close();
throw new ArchiveCorruptedException("The size of $file changed while reading, archive corrupted. read $read expected ".$fileinfo->getSize());
}
if(is_callable($this->callback)) {
call_user_func($this->callback, $fileinfo);
}
} | php | public function addFile($file, $fileinfo = '')
{
if (is_string($fileinfo)) {
$fileinfo = FileInfo::fromPath($file, $fileinfo);
}
if ($this->closed) {
throw new ArchiveIOException('Archive has been closed, files can no longer be added');
}
$fp = @fopen($file, 'rb');
if (!$fp) {
throw new ArchiveIOException('Could not open file for reading: '.$file);
}
// create file header
$this->writeFileHeader($fileinfo);
// write data
$read = 0;
while (!feof($fp)) {
$data = fread($fp, 512);
$read += strlen($data);
if ($data === false) {
break;
}
if ($data === '') {
break;
}
$packed = pack("a512", $data);
$this->writebytes($packed);
}
fclose($fp);
if($read != $fileinfo->getSize()) {
$this->close();
throw new ArchiveCorruptedException("The size of $file changed while reading, archive corrupted. read $read expected ".$fileinfo->getSize());
}
if(is_callable($this->callback)) {
call_user_func($this->callback, $fileinfo);
}
} | [
"public",
"function",
"addFile",
"(",
"$",
"file",
",",
"$",
"fileinfo",
"=",
"''",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"fileinfo",
")",
")",
"{",
"$",
"fileinfo",
"=",
"FileInfo",
"::",
"fromPath",
"(",
"$",
"file",
",",
"$",
"fileinfo",
"... | Add a file to the current TAR archive using an existing file in the filesystem
@param string $file path to the original file
@param string|FileInfo $fileinfo either the name to us in archive (string) or a FileInfo oject with all meta data, empty to take from original
@throws ArchiveCorruptedException when the file changes while reading it, the archive will be corrupt and should be deleted
@throws ArchiveIOException there was trouble reading the given file, it was not added
@throws FileInfoException trouble reading file info, it was not added | [
"Add",
"a",
"file",
"to",
"the",
"current",
"TAR",
"archive",
"using",
"an",
"existing",
"file",
"in",
"the",
"filesystem"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Tar.php#L249-L291 | train |
splitbrain/php-archive | src/Tar.php | Tar.getArchive | public function getArchive()
{
$this->close();
if ($this->comptype === Archive::COMPRESS_AUTO) {
$this->comptype = Archive::COMPRESS_NONE;
}
if ($this->comptype === Archive::COMPRESS_GZIP) {
return gzencode($this->memory, $this->complevel);
}
if ($this->comptype === Archive::COMPRESS_BZIP) {
return bzcompress($this->memory);
}
return $this->memory;
} | php | public function getArchive()
{
$this->close();
if ($this->comptype === Archive::COMPRESS_AUTO) {
$this->comptype = Archive::COMPRESS_NONE;
}
if ($this->comptype === Archive::COMPRESS_GZIP) {
return gzencode($this->memory, $this->complevel);
}
if ($this->comptype === Archive::COMPRESS_BZIP) {
return bzcompress($this->memory);
}
return $this->memory;
} | [
"public",
"function",
"getArchive",
"(",
")",
"{",
"$",
"this",
"->",
"close",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"comptype",
"===",
"Archive",
"::",
"COMPRESS_AUTO",
")",
"{",
"$",
"this",
"->",
"comptype",
"=",
"Archive",
"::",
"COMPRESS_NO... | Returns the created in-memory archive data
This implicitly calls close() on the Archive
@throws ArchiveIOException | [
"Returns",
"the",
"created",
"in",
"-",
"memory",
"archive",
"data"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Tar.php#L371-L386 | train |
splitbrain/php-archive | src/Tar.php | Tar.save | public function save($file)
{
if ($this->comptype === Archive::COMPRESS_AUTO) {
$this->setCompression($this->complevel, $this->filetype($file));
}
if (!@file_put_contents($file, $this->getArchive())) {
throw new ArchiveIOException('Could not write to file: '.$file);
}
} | php | public function save($file)
{
if ($this->comptype === Archive::COMPRESS_AUTO) {
$this->setCompression($this->complevel, $this->filetype($file));
}
if (!@file_put_contents($file, $this->getArchive())) {
throw new ArchiveIOException('Could not write to file: '.$file);
}
} | [
"public",
"function",
"save",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"comptype",
"===",
"Archive",
"::",
"COMPRESS_AUTO",
")",
"{",
"$",
"this",
"->",
"setCompression",
"(",
"$",
"this",
"->",
"complevel",
",",
"$",
"this",
"->",
"... | Save the created in-memory archive data
Note: It more memory effective to specify the filename in the create() function and
let the library work on the new file directly.
@param string $file
@throws ArchiveIOException
@throws ArchiveIllegalCompressionException | [
"Save",
"the",
"created",
"in",
"-",
"memory",
"archive",
"data"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Tar.php#L398-L407 | train |
splitbrain/php-archive | src/Tar.php | Tar.readbytes | protected function readbytes($length)
{
if ($this->comptype === Archive::COMPRESS_GZIP) {
return @gzread($this->fh, $length);
} elseif ($this->comptype === Archive::COMPRESS_BZIP) {
return @bzread($this->fh, $length);
} else {
return @fread($this->fh, $length);
}
} | php | protected function readbytes($length)
{
if ($this->comptype === Archive::COMPRESS_GZIP) {
return @gzread($this->fh, $length);
} elseif ($this->comptype === Archive::COMPRESS_BZIP) {
return @bzread($this->fh, $length);
} else {
return @fread($this->fh, $length);
}
} | [
"protected",
"function",
"readbytes",
"(",
"$",
"length",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"comptype",
"===",
"Archive",
"::",
"COMPRESS_GZIP",
")",
"{",
"return",
"@",
"gzread",
"(",
"$",
"this",
"->",
"fh",
",",
"$",
"length",
")",
";",
"}",... | Read from the open file pointer
@param int $length bytes to read
@return string | [
"Read",
"from",
"the",
"open",
"file",
"pointer"
] | 10d89013572ba1f4d4ad7fcb74860242f4c3860b | https://github.com/splitbrain/php-archive/blob/10d89013572ba1f4d4ad7fcb74860242f4c3860b/src/Tar.php#L415-L424 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.