datatable.directory codebase
https://datatable.directory/
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
119 lines
2.9 KiB
119 lines
2.9 KiB
6 years ago
|
<?php
|
||
|
|
||
|
|
||
|
namespace App\Tables;
|
||
|
|
||
|
|
||
|
class CStructArrayExporter extends BaseExporter
|
||
|
{
|
||
|
/**
|
||
|
* @return string - mime type for the downloaded file
|
||
|
*/
|
||
|
protected function getMimeType()
|
||
|
{
|
||
|
return $this->wantDownload ? 'text/x-csrc' : 'text/plain';
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* @return string - file extension for the downloaded file
|
||
|
*/
|
||
|
protected function getFileExtension()
|
||
|
{
|
||
|
return 'c';
|
||
|
}
|
||
|
|
||
|
private function cify($name)
|
||
|
{
|
||
|
$name = preg_replace('/[^a-z0-9_]/i', '_', $name);
|
||
|
if (ctype_digit($name[0])) {
|
||
|
$name = '_' . $name;
|
||
|
}
|
||
|
return $name;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Write the document to stdout ('php://output')
|
||
|
*/
|
||
|
protected function writeDocument()
|
||
|
{
|
||
|
$fields = array_map(function (Column $c) {
|
||
|
$type = $c->type;
|
||
|
if ($type == 'string') {
|
||
|
$type = 'const char *';
|
||
|
}
|
||
|
|
||
|
$name = $this->cify($c->name);
|
||
|
|
||
|
return (object)['name' => $c->name, 'type' => $c->type, 'ctype' => $type, 'cname' => $name];
|
||
|
}, $this->columns);
|
||
|
|
||
|
$ctablename = $this->cify($this->table->name);
|
||
|
|
||
|
// preamble
|
||
|
echo "#include <stdbool.h>\n\n";
|
||
|
|
||
|
echo "struct " . $ctablename . " {\n";
|
||
|
foreach ($fields as $field) {
|
||
|
echo " " . $field->ctype . " " . $field->cname . ";\n";
|
||
|
}
|
||
|
echo "};\n\n";
|
||
|
|
||
|
// Now the table itself
|
||
|
echo "const struct ".$ctablename.' tbl_'.$ctablename."[] = {\n";
|
||
|
|
||
|
$first = true;
|
||
|
foreach ($this->iterateRows() as $row) {
|
||
|
if ($first) {
|
||
|
$first = false;
|
||
|
} else {
|
||
|
echo ",\n";
|
||
|
}
|
||
|
|
||
|
echo " {";
|
||
|
|
||
|
$firstf = true;
|
||
|
foreach ($fields as $field) {
|
||
|
if ($firstf) {
|
||
|
$firstf = false;
|
||
|
} else {
|
||
|
echo ", ";
|
||
|
}
|
||
|
|
||
|
$val = 0;
|
||
|
switch ($field->type) {
|
||
|
case 'string':
|
||
|
$val = "";
|
||
|
break;
|
||
|
|
||
|
case 'bool':
|
||
|
$val = false;
|
||
|
break;
|
||
|
}
|
||
|
|
||
|
if (isset($row->{$field->name})) {
|
||
|
$val = $row->{$field->name};
|
||
|
}
|
||
|
|
||
|
// export to C format
|
||
|
switch ($field->type) {
|
||
|
case 'string':
|
||
|
echo '"' . addcslashes($val, "\0..\37!@\@\177..\377") . '"';
|
||
|
break;
|
||
|
|
||
|
case 'bool':
|
||
|
echo (int)$val;
|
||
|
break;
|
||
|
|
||
|
case 'int':
|
||
|
case 'float':
|
||
|
echo $val;
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
echo "}";
|
||
|
}
|
||
|
|
||
|
echo "\n};\n";
|
||
|
}
|
||
|
}
|