Skip to content

add trait for row to string converting without file #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions src/CsvRowUtil.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php
/**
* TODO:
*
*/

namespace Keboola\Csv;


trait CsvRowUtil
{
/**
* @param array $row
* @return string
* @throws Exception
*/
public function rowToStr(array $row)
{
$return = [];
foreach ($row as $column) {
if (!(
is_scalar($column)
|| is_null($column)
|| (
is_object($column)
&& method_exists($column, '__toString')
)
)) {
throw new Exception(
"Cannot write data into column: " . var_export($column, true),
Exception::WRITE_ERROR
);
}

$return[] = $this->getEnclosure() .
str_replace($this->getEnclosure(), str_repeat($this->getEnclosure(), 2), $column) .
$this->getEnclosure();
}
return implode($this->getDelimiter(), $return) . $this->getLineBreak();
}

/**
* TODO:
*
* @return mixed
*/
abstract protected function getDelimiter();

/**
* TODO:
*
* @return mixed
*/
abstract protected function getLineBreak();

/**
* TODO:
*
* @return mixed
*/
abstract protected function getEnclosure();

}
33 changes: 8 additions & 25 deletions src/CsvWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

class CsvWriter extends AbstractCsvFile
{
use CsvRowUtil;

/**
* @var string
*/
Expand Down Expand Up @@ -97,33 +99,14 @@ public function writeRow(array $row)
}
}


/**
* @param array $row
* @return string
* @throws Exception
* TODO:
*
* @return mixed
*/
public function rowToStr(array $row)
protected function getLineBreak()
{
$return = [];
foreach ($row as $column) {
if (!(
is_scalar($column)
|| is_null($column)
|| (
is_object($column)
&& method_exists($column, '__toString')
)
)) {
throw new Exception(
"Cannot write data into column: " . var_export($column, true),
Exception::WRITE_ERROR
);
}

$return[] = $this->getEnclosure() .
str_replace($this->getEnclosure(), str_repeat($this->getEnclosure(), 2), $column) .
$this->getEnclosure();
}
return implode($this->getDelimiter(), $return) . $this->lineBreak;
return $this->lineBreak;
}
}