Esempio n. 1
0
 public function testCsvSingleFileByFilenameFetcherManipulator()
 {
     $settings = array('FETCHER' => array('input_file' => dirname(__FILE__) . '/assets/csv/sample_metadata.csv', 'temp_directory' => $this->path_to_temp_dir, 'record_key' => 'ID', 'use_cache' => false), 'LOGGING' => array('path_to_log' => $this->path_to_log, 'path_to_manipulator_log' => ''), 'FILE_GETTER' => array('file_name_field' => 'File'), 'MANIPULATORS' => array('fetchermanipulators' => array('CsvSingleFileByFilename|postcard_1')));
     $csv = new Csv($settings);
     $records = $csv->getRecords();
     $this->assertCount(10, $records, "CsvSingleFileByFilename manipulator did not work");
 }
Esempio n. 2
0
 public function testGetItemInfo()
 {
     $settings = array('FETCHER' => array('input_file' => dirname(__FILE__) . '/assets/csv/sample_metadata.csv', 'record_key' => 'ID', 'temp_directory' => $this->path_to_temp_dir), 'LOGGING' => array('path_to_log' => $this->path_to_log));
     $csv = new Csv($settings);
     $record = $csv->getItemInfo('postcard_3');
     $this->assertEquals('1947', $record->Date, "Record date is not 1947");
 }
Esempio n. 3
0
 public function testGetRecords()
 {
     // We define settings here, not in a settings file.
     $settings = array('FETCHER' => array('input_file' => dirname(__FILE__) . '/assets/test.csv'));
     $a = new Csv($settings);
     $records = $a->getRecords();
     $this->assertCount(3, $records);
 }
Esempio n. 4
0
 public function testFromString()
 {
     $data = 'name;value' . "\n" . 'Foo;1' . "\n" . 'Bar;2' . "\n" . 'Baz;3' . "\n";
     $items = $this->reader->fromString($data);
     $this->assertCount(3, $items);
     $this->assertEquals('Foo', $items[0]['name']);
     $this->assertEquals(1, $items[0]['value']);
 }
Esempio n. 5
0
 public function testConstructor()
 {
     $contents = file_get_contents(__DIR__ . '/../data/read_sc.csv');
     $csv = new Csv($contents, ";");
     $expected = array(array("column1" => "1column2value", "column2" => "1column3value", "column3" => "1column4value"), array("column1" => "2column2value", "column2" => "2column3value", "column3" => "2column4value"), array("column1" => "3column2value", "column2" => "3column3value", "column3" => "3column4value"), array("column1" => "4column2value", "column2" => "4column3value", "column3" => "4column4value"), array("column1" => "5column2value", "column2" => "5column3value", "column3" => "5column4value"));
     $this->assertEquals($expected, $csv->toPrimitiveArray());
     try {
         $csv = new Csv("name,age\nhassan");
         $this->fail("should catch error");
     } catch (\ErrorException $e) {
     }
 }
Esempio n. 6
0
File: app.php Progetto: BernanR/ipvd
 public function upload_arquivo()
 {
     if (isset($_POST["submit"])) {
         $file = $_FILES;
         if ($file['file']['name'] == '') {
             $this->base->set_msg('error', "Selecione um arquivo csv");
         } else {
             $this->base->load_helper('csv');
             $csv = new Csv();
             if ($csv->upload()) {
                 $this->inserir($file['file']['name']);
             }
         }
     }
 }
Esempio n. 7
0
 /**
  * @dataProvider \g105b\phpcsv\TestHelper::data_randomFilePath
  */
 public function testUpdateRowWithMissingFields($filePath)
 {
     TestHelper::createCsv($filePath);
     $csv = new Csv($filePath);
     $csv->setIdField("rowNum");
     $row = $csv->get(3);
     $newFirstName = "Updated-" . $row["firstName"];
     $row["firstName"] = $newFirstName;
     $existingLastName = $row["lastName"];
     unset($row["lastName"]);
     $updated = $csv->update($row);
     $this->assertTrue($updated);
     $row = $csv->get(3);
     $this->assertEquals($newFirstName, $row["firstName"]);
     $this->assertEquals($existingLastName, $row["lastName"]);
 }
 public function testContentHeader()
 {
     $csv = Csv::create(false);
     $this->assertEquals($csv->getContentTypeHeader()->toString(), 'text/csv; header="absent"');
     $csv = Csv::create(true);
     $this->assertEquals($csv->getContentTypeHeader()->toString(), 'text/csv; header="present"');
 }
Esempio n. 9
0
 public function import($table, $fileName)
 {
     parent::__construct($fileName);
     $qwery = " ";
     $j = 1;
     for ($i = 1; $i < parent::getNumRows(); $i++) {
         $qwery = "INSERT INTO `mail_data`(`comp_name`, `email`, `phone`, `adres`, `called`, `sended`, `coments`) \n\t\t\tVALUES (";
         while (parent::issetCell($i, $j)) {
             $item = parent::getCellValue($i, $j);
             if ($j == 1) {
                 $qwery = $qwery . "'" . $this->mysqli->real_escape_string($item) . "'";
             } else {
                 $qwery = $qwery . ",'" . $this->mysqli->real_escape_string($item) . "'";
             }
             $j++;
         }
         $qwery = $qwery . ", '0', '0', NULL)";
         $result = $this->mysqli->query($qwery);
         if ($result === false) {
             echo 'Nie można było wykonać zapytania z powodu błędu: ' . $this->mysqli->error;
             exit(1);
         }
         $j = 1;
     }
     return true;
 }
Esempio n. 10
0
 public function index($table_name = null)
 {
     $files = Csv::getCsvFiles();
     //edit for tab display
     foreach ($files as $file) {
         $tabs[] = substr($file, 0, -4);
     }
     if (Request::ajax()) {
         if (Input::has('tab')) {
             $table_name = Input::get('tab');
             //replace the tab variable stored in the session
             Session::put('table_name', $table_name);
         } else {
             if (Input::has('page')) {
                 //return Input::get('page');
                 $table_name = Session::get('table_name');
             }
         }
         //get the contents of the file
         $data = Csv::getCsvContents($table_name . '.csv');
         //return an object containing data
         $dataObject = Csv::prepareData($data);
         //display working with correct pagination - will not actually work tho
         $paginator = CustomPagination::createPagination($dataObject, Input::get('page'));
         return View::make('layouts.table')->with('paginator', $paginator)->with('heading', $dataObject->tableHeading)->with('colHeadings', $dataObject->colHeadings);
     }
     //no requests made then reset the session variable
     Session::put('table_name', $tabs[0]);
     $data = $table_name == null ? Csv::getCsvContents($files[0]) : Csv::getCsvContents($table_name . '.csv');
     $dataObject = Csv::prepareData($data);
     //no input given defaults to 1
     $input = Input::get('page', 1);
     $paginator = CustomPagination::createPagination($dataObject, $input);
     return View::make('home.index')->with('tabs', $tabs)->with('paginator', $paginator)->with('heading', $dataObject->tableHeading)->with('colHeadings', $dataObject->colHeadings);
 }
Esempio n. 11
0
function getCsv($entity, $metric, $endDate, $period)
{
    $csv = new Csv();
    $options = array();
    if ($period != '1-DAY') {
        $options['a'] = array("SUM");
    }
    if ($period == '1-WEEK') {
        $options['ai'] = '1-HOUR';
    } else {
        if ($period == '1-MONTH') {
            $options['ai'] = '1-DAY';
        }
    }
    $response = $csv->export($entity, $metric, $endDate, $period, $options);
    return $response;
}
Esempio n. 12
0
 /**
  * Send a CSV response
  *
  * @access public
  * @param  array    $data          Data to serialize in csv
  * @param  integer  $status_code   HTTP status code
  */
 public function csv(array $data, $status_code = 200)
 {
     $this->status($status_code);
     $this->nocache();
     header('Content-Type: text/csv');
     Csv::output($data);
     exit;
 }
Esempio n. 13
0
 public static function createFtpOrders($orders, $fulfillmentModel)
 {
     self::$_relationships = array();
     self::$updateOrders = array();
     foreach ($orders as $order) {
         if ($order['status'] == 'ok') {
             self::$updateOrders[] = $order['order_id'];
         }
         if ($order['ship_with'] && !isset($orders[$order['ship_with']])) {
             $orders[$order['order_id']]['ship_with'] = '';
         }
         if ($order['ship_with']) {
             self::$_relationships[$order['order_id']] = $order['ship_with'];
         }
     }
     self::$returnArray = array();
     foreach ($orders as $order) {
         if (!$order['shippable']) {
             continue;
         }
         if (isset($order['ship_with']) && $order['ship_with']) {
             $order['ship_with'] = self::find_main($order['ship_with']);
             if (isset(self::$returnArray[$order['ship_with']])) {
                 $orderFtpModel = self::$returnArray[$order['ship_with']];
                 $orderFtpModel->ship_with = true;
                 $orderFtpModel->fillProduct($order);
                 self::$returnArray[$order['ship_with']] = $orderFtpModel;
             } else {
                 $orderFtpModel = new OrderFTP();
                 $orderFtpModel->fillOrder($order);
                 $orderFtpModel->ship_with = true;
                 $orderFtpModel->fillProduct($order);
                 self::$returnArray[$order['ship_with']] = $orderFtpModel;
             }
         } else {
             $orderFtpModel = isset(self::$returnArray[$order['order_id']]) ? self::$returnArray[$order['order_id']] : new OrderFTP();
             $orderFtpModel->fillOrder($order);
             $orderFtpModel->ship_with = false;
             $orderFtpModel->fillProduct($order);
             self::$returnArray[$order['order_id']] = $orderFtpModel;
         }
     }
     $array = self::getOrdersArray();
     return Csv::saveCsv($array, $fulfillmentModel->csvFileName);
 }
Esempio n. 14
0
 /**
  * @dataProvider \g105b\phpcsv\TestHelper::data_randomFilePath
  */
 public function testDeleteByReferenceRemovesExpectedRow($filePath)
 {
     TestHelper::createCsv($filePath, 10);
     $csv = new Csv($filePath);
     $rowThree = $csv->get(3);
     $allRows = $csv->getAll();
     $this->assertContains($rowThree, $allRows);
     $csv->delete($rowThree);
     $allRowsAfterDelete = $csv->getAll();
     $this->assertNotContains($rowThree, $allRowsAfterDelete);
     $searchResult = $csv->getAllBy("firstName", $rowThree["firstName"]);
     $this->assertNotContains($rowThree, $searchResult);
 }
Esempio n. 15
0
 public static function printArray($array, $fields = array(), $fileName = "")
 {
     Csv::heades($fileName);
     $i = 0;
     foreach ($array as $item) {
         if (!$i) {
             $temp = array();
             foreach ($item as $k => $v) {
                 $temp[] = __($k);
             }
             echo implode(',', $temp) . "\r\n";
             unset($temp, $k, $v);
         }
         $temp = array();
         foreach ($item as $v) {
             $data = str_replace(",", ";", $v);
             array_push($temp, $data);
         }
         echo implode(',', $temp) . "\r\n";
         $i++;
     }
     die;
 }
Esempio n. 16
0
            }
            if ($key == 0) {
                $text .= '</tr>';
            } else {
                $text .= '</tr>';
            }
        }
        $text .= '</table>';
        $pdf = Pdf::createPdf($text, 'L');
        $file = http_post_data($filesystemURI . '/pdf', Pdf::encodePdf($pdf), true);
        $file = File::decodeFile($file);
        $file->setDisplayName('conditions.pdf');
        $file = File::encodeFile($file);
    } elseif (isset($_GET['downloadConditionCsv'])) {
        $csv = Csv::createCsv($rows);
        $file = http_post_data($filesystemURI . '/csv', Csv::encodeCsv($csv), true);
        $file = File::decodeFile($file);
        $file->setDisplayName('conditions.csv');
        $file = File::encodeFile($file);
    }
    echo $file;
    exit(0);
}
if (isset($_GET['sortby'])) {
    $condition_data['sortby'] = $_GET['sortby'];
}
if (isset($_GET['sortId'])) {
    $condition_data['sortId'] = $_GET['sortId'];
}
// construct a new header
$h = Template::WithTemplateFile('include/Header/Header.template.html');
Esempio n. 17
0
 /**
  * @param string $file
  * @param \Magento\Framework\Filesystem\Directory\Write $directory
  * @param string $options
  */
 public function __construct($file, \Magento\Framework\Filesystem\Directory\Write $directory, $options)
 {
     $zip = new \Magento\Framework\Archive\Zip();
     $file = $zip->unpack($directory->getRelativePath($file), $directory->getRelativePath(preg_replace('/\\.zip$/i', '.csv', $file)));
     parent::__construct($file, $directory, $options);
 }
Esempio n. 18
0
 function testDetectSeparator_ComaAndSemiColon()
 {
     $result = Csv::detectSeparator(dirname(__FILE__) . '/data/two-lines.csv');
     $this->assertEqual($result, ',');
     $result = Csv::detectSeparator(dirname(__FILE__) . '/data/semicolon-separator.csv');
     $this->assertEqual($result, ';');
 }
Esempio n. 19
0
 /**
  * 导入商品csv
  * */
 function upload_csv()
 {
     $mark = IReq::get('marked');
     $csvType = IReq::get('date_format');
     //调用文件上传类
     $uploadObj = new IUpload(10240, array('csv'));
     $uploadObj->setDir('upload/' . date('Y/m/d'));
     $photo = $uploadObj->execute();
     if (!isset($photo['attach'][0]['flag']) || $photo['attach'][0]['flag'] == '-1') {
         echo "<br /><div align='center'>请选择CSV文件</div>";
         exit;
     }
     //上传路径
     $csvfile = $photo['attach'][0]['fileSrc'];
     //创建csv对象
     $csvObj = new Csv();
     $if_sucee = $csvObj->import($csvType, $csvfile, $mark);
     if ($if_sucee == '0') {
         IFile::unlink($csvfile);
         //导入成功,删除csv文件
         echo "<br /><div align='center'>商品CSV导入成功</div>";
     } else {
         IFile::unlink($csvfile);
         //导入失败,删除csv文件
         echo "<br /><div align='center'>商品CSV导入失败</div>";
     }
 }
Esempio n. 20
0
 function testEscapedStringContainsLineFeed()
 {
     $writer = new Csv();
     $this->assertEquals("\"line1\nline2\"", $writer->escapeString("line1\nline2"));
 }
Esempio n. 21
0
File: bill.php Progetto: noikiy/nc-1
 /**
  * 导出结算退单明细CSV
  *
  */
 public function export_refund_orderOp()
 {
     if (!preg_match('/^20\\d{5,12}$/', $_GET['ob_no'])) {
         showMessage('参数错误', '', 'html', 'error');
     }
     $model_bill = Model('bill');
     $bill_info = $model_bill->getOrderBillInfo(array('ob_no' => $_GET['ob_no']));
     if (!$bill_info) {
         showMessage('参数错误', '', 'html', 'error');
     }
     $model_refund = Model('refund_return');
     $condition = array();
     $condition['seller_state'] = 2;
     $condition['store_id'] = $bill_info['ob_store_id'];
     $condition['goods_id'] = array('gt', 0);
     $if_start_date = preg_match('/^20\\d{2}-\\d{2}-\\d{2}$/', $_GET['query_start_date']);
     $if_end_date = preg_match('/^20\\d{2}-\\d{2}-\\d{2}$/', $_GET['query_end_date']);
     $start_unixtime = $if_end_date ? strtotime($_GET['query_start_date']) : null;
     $end_unixtime = $if_end_date ? strtotime($_GET['query_end_date']) : null;
     if ($if_end_date || $if_end_date) {
         $condition['admin_time'] = array('time', array($start_unixtime, $end_unixtime));
     } else {
         $condition['admin_time'] = array('time', array($bill_info['ob_start_date'], $bill_info['ob_end_date']));
     }
     if (!is_numeric($_GET['curpage'])) {
         $count = $model_refund->getRefundReturn($condition);
         $array = array();
         if ($count > self::EXPORT_SIZE) {
             //显示下载链接
             $page = ceil($count / self::EXPORT_SIZE);
             for ($i = 1; $i <= $page; $i++) {
                 $limit1 = ($i - 1) * self::EXPORT_SIZE + 1;
                 $limit2 = $i * self::EXPORT_SIZE > $count ? $count : $i * self::EXPORT_SIZE;
                 $array[$i] = $limit1 . ' ~ ' . $limit2;
             }
             Tpl::output('list', $array);
             Tpl::output('murl', 'index.php?act=bill&op=show_bill&query_type=refund&ob_no=' . $_GET['ob_no']);
             Tpl::showpage('export.excel');
             exit;
         } else {
             //如果数量小,直接下载
             $data = $model_refund->getRefundReturnList($condition, '', '*,refund_amount*commis_rate/100 as commis_amount', self::EXPORT_SIZE);
         }
     } else {
         //下载
         $limit1 = ($_GET['curpage'] - 1) * self::EXPORT_SIZE;
         $limit2 = self::EXPORT_SIZE;
         $data = $model_refund->getRefundReturnList(condition, '', '*,refund_amount*commis_rate/100 as commis_amount', "{$limit1},{$limit2}");
     }
     if (is_array($data) && count($data) == 1 && $data[0]['refund_id'] == '') {
         $refund_list = array();
     }
     $export_data = array();
     $export_data[0] = array('退单编号', '订单编号', '退单金额', '退单佣金', '类型', '退款日期', '商家', '商家编号', '买家', '买家编号');
     $refund_amount = 0;
     $commis_totals = 0;
     $k = 0;
     foreach ($data as $v) {
         $export_data[$k + 1][] = 'NC' . $v['refund_sn'];
         $export_data[$k + 1][] = 'NC' . $v['order_sn'];
         $refund_amount += $export_data[$k + 1][] = $v['refund_amount'];
         $commis_totals += $export_data[$k + 1][] = ncPriceFormat($v['commis_amount']);
         $export_data[$k + 1][] = str_replace(array(1, 2), array('退款', '退货'), $v['refund_type']);
         $export_data[$k + 1][] = date('Y-m-d', $v['admin_time']);
         $export_data[$k + 1][] = $v['store_name'];
         $export_data[$k + 1][] = $v['store_id'];
         $export_data[$k + 1][] = $v['buyer_name'];
         $export_data[$k + 1][] = $v['buyer_id'];
         $k++;
     }
     $count = count($export_data);
     $export_data[$count][] = '';
     $export_data[$count][] = '合计';
     $export_data[$count][] = $refund_amount;
     $export_data[$count][] = $commis_totals;
     $csv = new Csv();
     $export_data = $csv->charset($export_data, CHARSET, 'gbk');
     $csv->filename = $csv->charset('退单明细-', CHARSET) . $_GET['ob_no'];
     $csv->export($export_data);
 }
 public static function import($path_csv, $path_resources = null, $mapping = array())
 {
     $tag = "EntityImporter:import()";
     Log::notice("{$tag}: <{$path_csv}, {$path_resources}, {$mapping}>");
     // pseudo contants
     $IMPORT_MODE_INSERT = 0;
     $IMPORT_MODE_UPDATE = 1;
     // init results array
     $stat = array();
     $stat["attempts"] = 0;
     $stat["inserts"] = 0;
     $stat["updates"] = 0;
     $stat["warnings"] = 0;
     $stat["errors"] = 0;
     // TODO: include sub-arrays for warning messages and error messages
     // eg: $stat["warning_messages"] = array(); where array indecies reference csv row numbers
     if (!is_readable($path_csv)) {
         Log::error("{$tag}: Unable to read from path {$path_csv}");
         throw new Exception("{$tag}: Unable to read from path {$path_csv}");
     }
     if ($path_resources != null && !is_readable($path_resources)) {
         Log::error("{$tag}: Unable to read from path {$path_resources}");
         throw new Exception("{$tag}: Unable to read from path {$path_resources}");
     }
     $csv_filename = basename($path_csv);
     $blueprint_key = substr($csv_filename, 0, strpos($csv_filename, "."));
     $blueprint_signature = $blueprint_key . ".entity.xml";
     Log::debug("{$tag}: Blueprint Signature: {$blueprint_signature}");
     /*
     // Compare CSV Header with Blueprint
     // determine if mapping is required
     */
     // read blueprint (on server)
     $bp = BlueprintReader::read($blueprint_signature);
     // init csv file for parsing
     $csv = new Csv($path_csv);
     // read csv header row
     $csv_header_row = $csv->nextRow();
     // apply mappings
     for ($i = 0; $i < count($csv_header_row); $i++) {
         $import_field = $csv_header_row[$i];
         $mapping_key = "mapping_" . $bp->getKey() . "_" . str_replace(".", "_", $import_field);
         // skip <id> columns
         if ($import_field == "id") {
             continue;
         }
         // skip columns where mapping is _DROP
         if (array_key_exists($mapping_key, $mapping) && $mapping[$mapping_key] == "_DROP") {
             continue;
         }
         if (array_key_exists($mapping_key, $mapping)) {
             // replace csv column header with mapped value
             $csv_header_row[$i] = $mapping["{$mapping_key}"];
         }
     }
     foreach ($csv_header_row as $import_field) {
         // skip <id> columns
         if ($import_field == "id") {
             continue;
         }
         // skip columns where mapping is _DROP
         $mapping_key = "mapping_" . $bp->getKey() . "_" . str_replace(".", "_", $import_field);
         if (array_key_exists($mapping_key, $mapping) && $mapping[$mapping_key] == "_DROP") {
             continue;
         }
         if (!$bp->keyExists($import_field)) {
             throw new EntityImporterException($bp, $csv_header_row);
         }
     }
     // check for id column
     $with_ids = false;
     if (in_array("id", $csv_header_row)) {
         $with_ids = true;
         Log::debug("{$tag}: Importing with ids");
     }
     // init Entity DAO
     $entityDAO = new EntityDAO($bp);
     // Import rows from Csv
     while (($row = $csv->nextRow()) !== FALSE) {
         $stat["attempts"]++;
         // init an entity to import
         unset($entity);
         // clear previous
         $entity = null;
         // flag an import mode (insert, update)
         $import_mode = EntityImporter::$IMPORT_MODE_INSERT;
         // check <id> to see if this csv row references an existing entity
         if ($with_ids) {
             $import_id = $row[0];
             if (!empty($import_id) && $import_id != 0) {
                 // check that an entity with this id exists
                 try {
                     if ($match = $entityDAO->load($import_id)) {
                         $entity = $match;
                         $import_mode = EntityImporter::$IMPORT_MODE_UPDATE;
                         Log::debug("{$tag}: Updating an existing {$blueprint_signature} with id {$import_id}");
                     } else {
                         $entity = $bp->build();
                         $entity->setId($import_id);
                         Log::debug("{$tag}: Creating a new {$blueprint_signature} with id {$import_id}");
                     }
                 } catch (Exception $e) {
                     $stat["warnings"]++;
                     Log::warning("{$tag}: Caught Exception: " . $e->getMessage());
                     $entity = $bp->build();
                     $entity->setId($import_id);
                     Log::debug("{$tag}: Creating a new {$blueprint_signature} with id {$import_id}");
                 }
             }
             // END: if( (!empty($import_id)) && ($import_id!=0) )
         }
         // END: if($with_ids)
         // if we are not working with an existing entity, build a new one
         if ($entity == null) {
             $entity = $bp->build();
             Log::debug("{$tag}: Creating a new {$blueprint_signature} without an id");
         }
         for ($i = 0; $i < count($csv_header_row); $i++) {
             // extract data from csv
             $import_field_key = $csv_header_row[$i];
             $import_field_value = $row[$i];
             // skid <id> column
             if ($import_field_key == "id") {
                 continue;
             }
             // skip columns where mapping is _DROP
             $mapping_key = "mapping_" . $bp->getKey() . "_" . str_replace(".", "_", $import_field_key);
             if (array_key_exists($mapping_key, $mapping) && $mapping[$mapping_key] == "_DROP") {
                 continue;
             }
             // extract field information from blueprint
             $field = $bp->get($import_field_key);
             switch ($field->getDataType()) {
                 case "date":
                     // reformat dates for mysql
                     $time = strtotime($import_field_value);
                     $import_field_value = date("Y-m-d", $time);
                     $entity->set($import_field_key, $import_field_value);
                     break;
                 case "binary":
                     $path_binary = $path_resources . $import_field_value;
                     Log::debug("{$tag}: Searching for binary at path {$path_binary}");
                     if (is_readable($path_binary)) {
                         Log::debug("{$tag}: Found readable binary at path {$path_binary}");
                         $binaryString = file_get_contents($path_binary);
                         $entity->set($import_field_key, $binaryString);
                     } else {
                         Log::debug("{$tag}: No readable binary at path {$path_binary}");
                     }
                     break;
                 default:
                     $entity->set($import_field_key, $import_field_value);
                     break;
             }
             // END: switch($field->getType())
         }
         // END: for($i=0; $i<count($csv_header_row); $i++)
         switch ($import_mode) {
             case EntityImporter::$IMPORT_MODE_UPDATE:
                 try {
                     $entityDAO->update($entity);
                     $stat["updates"]++;
                 } catch (Exception $e) {
                     Log::warning("{$tag}: Caught Exception: " . $e->getMessage());
                     $stat["errors"]++;
                 }
                 break;
             case EntityImporter::$IMPORT_MODE_INSERT:
                 try {
                     $entityDAO->insert($entity);
                     $stat["inserts"]++;
                 } catch (Exception $e) {
                     Log::warning("{$tag}: Caught Exception: " . $e->getMessage());
                     $stat["errors"]++;
                 }
                 break;
         }
     }
     // END: while( ($row = $csv->nextRow()) !== FALSE )
     return $stat;
 }
 /**
  * Imports Utilisateur entities.
  * Same method explained in CoursController.php
  * Parse CSV file
  * The CSV cours structure was defined with Christophe Widmer (please contact him for CSV examples and notices)
  * This one is a bit more complex
  * WARNING : each column has its own role, dont blend it
  *
  */
 public function importAction(Request $request)
 {
     $parser = new Csv();
     $type = 'text/plain';
     $ext = 'csv';
     $path = __DIR__ . '/../../../../web/uploads/csv';
     $em = $this->getDoctrine()->getManager();
     $form = $this->createForm(new CsvType());
     if ($request->getMethod() == 'POST') {
         $form->bind($request);
         if ($form->isValid()) {
             $data = $form->getData();
             $file = $data['csv']->move($path, 'temp.csv');
             $parser->set($path, 'temp.csv');
             $rows = $parser->parseCsv();
             $length = count($rows);
             foreach ($rows as $row) {
                 $statement = array();
                 foreach ($row as $cell) {
                     $cell = trim($cell);
                     $statement[] = empty($cell);
                 }
                 if (in_array(true, $statement)) {
                     $length--;
                 } else {
                     $role = $em->getRepository('AppCoreBundle:Role')->findOneBy(array('name' => $row[4]));
                     if (!empty($role)) {
                         $entity = new Utilisateur();
                         $entity->setLastname($row[0]);
                         $entity->setFirstname($row[1]);
                         $entity->setUsername($row[2]);
                         $entity->setEmail($row[3]);
                         $entity->setRole($role);
                         $entity->setPassword($row[5]);
                         $factory = $this->get('security.encoder_factory');
                         $encoder = $factory->getEncoder($entity);
                         $entity->setSalt(md5(time()));
                         $entity->setPassword($encoder->encodePassword($entity->getPassword(), $entity->getSalt()));
                         $validator = $this->get('validator');
                         if (!count($validator->validate($entity))) {
                             $em->persist($entity);
                         } else {
                             $length--;
                         }
                     } else {
                         $length--;
                     }
                 }
             }
             $em->flush();
             if (file_exists($path . '/temp.csv')) {
                 unlink($path . '/temp.csv');
             }
             $this->get('session')->getFlashBag()->add('success', $length . ' utilisateurs ont été ajoutés !');
             return $this->redirect($this->generateUrl('utilisateur_import'));
         }
     }
     return $this->render('AppCoreBundle:Utilisateur:import.html.twig', array('headline' => 'Utilisateurs', 'title' => 'Importer des utilisateurs', 'form' => $form->createView()));
 }
Esempio n. 24
0
 private function csvReport($dataProvider, $reportName, $headers = array())
 {
     Csv::heades($reportName);
     if ($headers) {
         echo implode(',', array_keys($headers)) . "\r\n";
     }
     foreach ($dataProvider as $dp) {
         echo implode(',', $dp) . "\r\n";
     }
     die;
 }
Esempio n. 25
0
 /**
  * 导出结算订单明细CSV
  *
  */
 public function export_orderOp()
 {
     if (!preg_match('/^20\\d{5,12}$/', $_GET['ob_no'])) {
         showMessage('参数错误', '', 'html', 'error');
     }
     if (substr($_GET['ob_no'], 6) != $_SESSION['store_id']) {
         showMessage('参数错误', '', 'html', 'error');
     }
     $model_bill = Model('vr_bill');
     $bill_info = $model_bill->getOrderBillInfo(array('ob_no' => $_GET['ob_no']));
     if (!$bill_info) {
         showMessage('参数错误', '', 'html', 'error');
     }
     $model_order = Model('vr_order');
     $condition = array();
     $condition['store_id'] = $_SESSION['store_id'];
     if (preg_match('/^\\d{8,20}$/', $_GET['query_order_no'])) {
         //取order_id
         $order_info = $model_order->getOrderInfo(array('order_sn' => $_GET['query_order_no']), 'order_id');
         $condition['order_id'] = $order_info['order_id'];
     }
     $if_start_date = preg_match('/^20\\d{2}-\\d{2}-\\d{2}$/', $_GET['query_start_date']);
     $if_end_date = preg_match('/^20\\d{2}-\\d{2}-\\d{2}$/', $_GET['query_end_date']);
     $start_unixtime = $if_start_date ? strtotime($_GET['query_start_date']) : null;
     $end_unixtime = $if_end_date ? strtotime($_GET['query_end_date']) : null;
     if ($if_start_date || $if_end_date) {
         $condition_time = array('time', array($start_unixtime, $end_unixtime));
     } else {
         $condition_time = array('between', "{$bill_info['ob_start_date']},{$bill_info['ob_end_date']}");
     }
     if ($_GET['type'] == 'timeout') {
         //计算未使用已过期不可退兑换码列表
         $condition['vr_state'] = 0;
         $condition['vr_invalid_refund'] = 0;
         $condition['vr_indate'] = $condition_time;
     } else {
         //计算已使用兑换码列表
         $condition['vr_state'] = 1;
         $condition['vr_usetime'] = $condition_time;
     }
     if (!is_numeric($_GET['curpage'])) {
         $count = $model_order->getOrderCodeCount($condition);
         $array = array();
         if ($count > self::EXPORT_SIZE) {
             //显示下载链接
             $page = ceil($count / self::EXPORT_SIZE);
             for ($i = 1; $i <= $page; $i++) {
                 $limit1 = ($i - 1) * self::EXPORT_SIZE + 1;
                 $limit2 = $i * self::EXPORT_SIZE > $count ? $count : $i * self::EXPORT_SIZE;
                 $array[$i] = $limit1 . ' ~ ' . $limit2;
             }
             Tpl::output('list', $array);
             Tpl::output('murl', 'index.php?act=store_vr_bill&op=show_bill&ob_no=' . $_GET['ob_no']);
             Tpl::showpage('store_export.excel');
             exit;
         } else {
             //如果数量小,直接下载
             $data = $model_order->getCodeList($condition, '*', '', 'rec_id desc', self::EXPORT_SIZE);
         }
     } else {
         //下载
         $limit1 = ($_GET['curpage'] - 1) * self::EXPORT_SIZE;
         $limit2 = self::EXPORT_SIZE;
         $data = $model_order->getCodeList($condition, '*', '', 'rec_id desc', "{$limit1},{$limit2}");
     }
     //然后取订单编号
     $order_id_array = array();
     if (is_array($data)) {
         foreach ($data as $code_info) {
             $order_id_array[] = $code_info['order_id'];
         }
     }
     $condition = array();
     $condition['order_id'] = array('in', $order_id_array);
     $order_list = $model_order->getOrderList($condition);
     $order_new_list = array();
     if (!empty($order_list)) {
         foreach ($order_list as $v) {
             $order_new_list[$v['order_id']]['order_sn'] = $v['order_sn'];
             $order_new_list[$v['order_id']]['buyer_name'] = $v['buyer_name'];
             $order_new_list[$v['order_id']]['buyer_id'] = $v['buyer_id'];
             $order_new_list[$v['order_id']]['store_name'] = $v['store_name'];
             $order_new_list[$v['order_id']]['store_id'] = $v['store_id'];
             $order_new_list[$v['order_id']]['goods_name'] = $v['goods_name'];
         }
     }
     $export_data = array();
     $export_data[0] = array('兑换码', '消费时间', '订单号', '消费金额', '佣金金额', '买家', '买家编号', '商品');
     if ($_GET['type'] == 'timeout') {
         $export_data[0][1] = '过期时间';
     }
     $pay_totals = 0;
     $commis_totals = 0;
     $k = 0;
     foreach ($data as $v) {
         //该订单算佣金
         $export_data[$k + 1][] = $v['vr_code'];
         if ($_GET['type'] == 'timeout') {
             $export_data[$k + 1][] = date('Y-m-d H:i:s', $v['vr_indate']);
         } else {
             $export_data[$k + 1][] = date('Y-m-d H:i:s', $v['vr_usetime']);
         }
         $export_data[$k + 1][] = 'NC' . $order_new_list[$v['order_id']]['order_sn'];
         $pay_totals += $export_data[$k + 1][] = floatval($v['pay_price']);
         $commis_totals += $export_data[$k + 1][] = floatval($v['pay_price'] * $v['commis_rate'] / 100);
         $export_data[$k + 1][] = $order_new_list[$v['order_id']]['buyer_name'];
         $export_data[$k + 1][] = $order_new_list[$v['order_id']]['buyer_id'];
         $export_data[$k + 1][] = $order_new_list[$v['order_id']]['goods_name'];
         $k++;
     }
     $count = count($export_data);
     $export_data[$count][] = '合计';
     $export_data[$count][] = '';
     $export_data[$count][] = '';
     $export_data[$count][] = $pay_totals;
     $export_data[$count][] = $commis_totals;
     $csv = new Csv();
     $export_data = $csv->charset($export_data, CHARSET, 'gbk');
     $file_name = $_GET['type'] == 'timeout' ? '过期兑换码列表' : '已消费兑换码列表';
     $csv->filename = $csv->charset($file_name . '-', CHARSET) . $_GET['ob_no'];
     $csv->export($export_data);
 }
Esempio n. 26
0
<?php
/*
* Case of use of Csv.class
* @package csv
* @date 2005-08-01
*/

require("_preload.php");

try {
    $Csv = new Csv($filename = "../../test/exportoutlook_1.CSV", $separator = ",");
    $csvData = $Csv->readAll();

    echo "<table border='1'>";
    foreach($csvData as $row) {
        echo "<tr>";
        foreach($row as $col) {
            echo "<td>$col</td>";
        }
        echo "</tr>";
    }
    echo "</table>";
}
catch (Exception $e) {
    echo "<hr />";
    echo "Exception code:  <font style='color:blue'>". $e->getCode() ."</font>";
    echo "<br />";
    echo "Exception message: <font style='color:blue'>". nl2br($e->getMessage()) ."</font>";
    echo "<br />";
    echo "Thrown by: '". $e->getFile() ."'";
    echo "<br />";
Esempio n. 27
0
 /**
  * Computes the dataTable output and returns the string/binary
  *
  * @return string
  */
 public function render()
 {
     return parent::render();
 }
Esempio n. 28
0
 /**
  * @dataProvider \g105b\phpcsv\TestHelper::data_randomFilePath
  * @expectedException \g105b\phpcsv\InvalidIndexException
  */
 public function testGetNonIntegerIndex_negative($filePath)
 {
     TestHelper::createCsv($filePath, 10);
     $csv = new Csv($filePath);
     $csv->get(-5);
 }
Esempio n. 29
0
 public function addLine(array $values)
 {
     foreach ($values as $key => $value) {
         $values[$key] = utf8_decode(Csv::escapeString($value));
     }
     $string = implode(',', $values) . "\r\n";
     fwrite($this->fileHandle, $string);
 }
Esempio n. 30
0
 public function getCsv($fields = null, $method = 'csvSelect')
 {
     $db = self::$_msql;
     if ($this->searchFields) {
         $this->createFilter();
     }
     if ($this->_where) {
         $where = implode(' ', $this->_where);
     } else {
         $where = '';
     }
     if ($fields && is_array($fields)) {
         $selectFields = implode(',', $fields);
     } else {
         $selectFields = '*';
     }
     $sql = $this->{$method}($selectFields, $where, $this->join);
     $result = $db->query($sql);
     $filename = $this->modelName;
     Csv::heades($filename);
     $i = 0;
     $model = new $this->modelName();
     $fieldsLable = $model->attributeLabels();
     while ($res = $db->fetch($result)) {
         if (!$i) {
             $temp = array();
             foreach ($res as $key => $value) {
                 $nkey = isset($fieldsLable[$key]) ? $fieldsLable[$key] : $key;
                 $temp[$nkey] = $value;
             }
             echo implode(',', array_keys($temp)) . "\r\n";
         }
         echo implode(',', $res) . "\r\n";
         $i++;
     }
     die;
 }