I use phpexcel in my project, if i call my class by my function, excel file cannot open
I call my class:
$Model = loadModel('cpm','cpm',$this->registry);
My function:
function loadModel($com='',$class_name='',$registry=null) {
if (empty($com)){
$com = 'admin';
}
$filename = strtolower($class_name) . '.class.php';
$file = PATH_MODEL.DS.$com.DS.$filename;
if (file_exists($file) == false){
return false;
}
require_once($file);
if($registry != NULL){
$model = new $class_name($registry);
}else{
$model = new $class_name;
}
return $model;
}
When i change to
/*require_once($file);
if($registry != NULL){
$model = new $class_name($registry);
}else{
$model = new $class_name;
}*/
$model=true;
return $model;
it work. In my project, I use autoload:
function __autoload($class_name) {
/*** get the component from the url ***/
$com = (empty($_GET['com'])) ? '' : $_GET['com'];
if (empty($com)){
$com = 'admin';
}
$filename = strtolower($class_name) . '.class.php';
$file = PATH_MODEL.DS.$com.DS.$filename;
if (file_exists($file) == false){
return false;
}
requine_once ($file);
}
I am not sure it is reason.
I don't found any error in log.
Any help, thank.
I found that if I require(once) or include(once) file in controler, excel file will be can not open.
class excelController extends baseController {
public function index(){
require('abc.class.php');
$this->registry->template->show('excel', false);
}
}
It's probable that your autoloader is clashing with PHPExcel's autoloader. See section 3.2 of the developer documentation (entitled "Lazy Loader") for advice on registering your own autoloader with spl_autoload_register() so that the two can co-exist
Related
I'm turning again on you guys, because I spend my fair share of hours on this "task" and I still can't figure out how to test my service method, without my function connection on database (I have to mock repository functions)
This is my service function
public function getInfo($history, $name)
{
$requestRepository = $this->em->getRepository(Request::class);
if ($history) {
$requests = [];
foreach ($requestRepository->getRequestsByName($name) as $request) {
$requests[] = $requestRepository->transform($request);
}
return $requests;
} else {
$request = $requestRepository->getCompletedRequestByName($name);
if (!is_null($request)) {
return $requestRepository->transform($request);
} else {
return null;
}
}
}
And this is my test
public function testGetInfo()
{
/* This returns errors, because it tries to connect to DATABASE, but I don't wan't that, that's why I figure out I need to mock this
$requestManager = new RequestManager($this->entityManager);
$test = $requestManager->getInfo('histroy', 'antrax.com');
*/
$requestManager = $this->getMockBuilder(RequestManager::class)->disableOriginalConstructor()->setMethods(['getInfo'])
->getMock();
// And rest of this are just my FAILED attempts to figure out, how to test my methods
$queryBuilder = $this->getMockBuilder(RequestRepository::class)->disableOriginalConstructor()
->setMethods(['getInfo'])->getMock();
$test = $queryBuilder->method('getInfo')->willReturnSelf();
$queryBuilder->method('getInfo')->willReturnCallback(function ($field, $value) use ($queryBuilder, $test){
if ($field == 'newStatus') {
$this->assertSame('EXPIRED', $value);
}
return $queryBuilder;
});
}
Can some one please help me how to write a test for my method getInfo so it will have 100% cover. If you need any additional informations, please let me know and I will provide. Thank you!
This is an answer to my problem
public function testGetInfo()
{
$mockEntity = $this->mockEntityManager;
$name = 'antrax.com';
$requestMock = new RequestEntity();
$transformedRequest = [
'id' => 1
];
$requestRepo = $this->getMockBuilder(RequestRepository::class)->disableOriginalConstructor()
->setMethods(['getRequestsByName', 'transform', 'getCompletedRequestByName'])->getMock();
$requestRepo->method('getRequestsByName')->willReturnCallback(function ($passedName) use ($name, $requestMock) {
$this->assertSame($name, $passedName);
return [$requestMock, $requestMock];
});
$requestRepo->method('transform')->willReturnCallback(function ($request) use ($requestMock, $transformedRequest) {
$this->assertSame($requestMock, $request);
return $transformedRequest;
});
$i = 0;
$requestRepo->method('getCompletedRequestByName')->willReturnCallback(function ($passedName) use ($name, $requestMock, &$i) {
$this->assertSame($name, $passedName);
if ($i == 0) {
$i+=1;
return null;
} else {
return $requestMock;
}
});
$mockEntity->method('getRepository')->willReturnCallback(function ($requestClass) use ($requestRepo) {
$this->assertSame(RequestEntity::class, $requestClass);
return $requestRepo;
});
$requestManager = new RequestManager($mockEntity);
$this->assertSame([$transformedRequest, $transformedRequest], $requestManager->getInfo(true, $name));
$this->assertNull($requestManager->getInfo(false, $name));
$this->assertSame($transformedRequest, $requestManager->getInfo(false, $name));
}
Without Symfony, this is how I post excel data to database.
// Include PHPExcel_IOFactory
require_once ('../Classes/PHPExcel/IOFactory.php');
$inputFileName = 'abc.xls';
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Insert row data array into your database of choice here
}
Now with the ExcelBundle, I am stuck. The documentation doesn't help me at all in this task. I've tried every advice given in similar questions and I cant manage to do this.
Creating an object from a file like the example below doesn't work at all:
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject('file.xls');
How to achieve this task?
I worked this out as follows:
Make sure the path Liuggio/ExcelBundle/Controller/FakeController.php exists
Make sure you update the app/config config.yml and routing.yml are updated with the provided files (Liuggio/ExcelBundle/Tests/app)
Assuming that you are updating the product table, Update the FakeController as follows:
<?php
namespace Liuggio\ExcelBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Product;
class FakeController extends Controller
{
public function insertAction()
{
$data = [];
$appPath = $this->container->getParameter('kernel.root_dir');
$file = realpath($appPath . '/../web/excelFiles/abc.xls');
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($file);
$sheet = $phpExcelObject->getActiveSheet()->toArray(null, true, true, true);
$em = $this->getDoctrine()->getManager();
$data['sheet'] = $sheet;
//READ EXCEL FILE CONTENT
foreach($sheet as $i=>$row) {
if($i !== 1) {
$product = new Product();
$product->setProductCode($row['A']);
$product->setProductName($row['B']);
$product->setProductRetailPrice($row['C']);
$product->setProductCost($row['D']);
$product->setProductTax($tax);
$product->setCategory($category);
//... and so on
$em->persist($product);
$em->flush();
//redirect appropriately
}
}
$data['obj'] = $phpExcelObject;
return $this->render('excel/read.html.twig', ['data' => $data ] );
}
}
I am virtually at a brick wall with Symfony, I have a folder at /../compiled/ with some minified files, and the controller is configured to get files from getRootDir() + /../compiled/file.min.css
However, it just throws out an exception 'file not found' when call file_get_contents(file) even when the file actually exists.
I just don't know what is wrong, it is such a cryptic problem.
Code as requested:
public function atpInitAction(Request $request) // Validates the origin.
{
$content = null; $_file = $request->query->get('file');
if ($_SERVER["SERVER_NAME"] == atpHandler::getDomain())
{
// I AM FROM THE ORIGIN...
$webfolder = $this->get('kernel')->getRootDir() . '/../compiled';
$_file = $webfolder."/".$_file;
}
// What's my mime?
$_mime = 'text/plain';
if ($_file[strlen($_file)-2] == 'j') { $_mime = 'text/javascript'; }
else { $_mime = 'text/css'; }
$response = new Response();
$response->headers->set('Content-Type', $_mime);
$response->headers->set('Content-Disposition', 'filename="'.basename($_file) . '";');
$response->headers->set('Content-Length', filesize($_file));
$response->setContent(file_get_contents($_file));
$response->sendHeaders();
return $response;
}
I have override the existing \yii\db\ActiveRecord with my own class. The method I've override is beforeSave(). I've read the documentation about the usage. But I found it's called twice when checking the record whether it is a new record or not.
This is my code:
class ActiveRecord extends \yii\db\ActiveRecord{
public $count = 0;
public function beforeSave($insert) {
print($this->count++); //i try to investigate it deeper using this "count" property
if(parent::beforeSave($insert)){
if($this->isNewRecord){
print("123"); //this printed out
if($this->hasAttribute('user_create')){
$this->user_create = \Yii::$app->user->identity->id;
}
if($this->hasAttribute('time_create')){
$this->time_create = new \yii\db\Expression('now()');
}
}
else{
print("456"); //and this is also
if($this->hasAttribute('user_upd')){
$this->user_upd = \Yii::$app->user->identity->id;
}
if($this->hasAttribute('time_upd')){
$this->time_upd = new \yii\db\Expression('now()');
}
}
return true;
}else{
return false;
}
}
}
and the output of the code when I do save a new record is as follow
01231456
I made a mistaken in the Controller Side, this is my Code
public function actionCreate() {
$model = new Grup();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if ($model->save()) {
echo Json::encode(array('status' => 1));
} else {
echo Json::encode(array('status' => 0, 'message' => \kartik\widgets\ActiveForm::validate($model)));
}
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
I shouldn't use $model->save() twice.
I have a form, PhotoForm, which has an emebedded BlobDataForm.
I can save the blbo data fine, my problem comes, with the blob_data table.
I have 2 fields, image_width and image_height.
I'd like to save these details as well, when the blob is saved.
I have overridden doSave();
protected function doSave($con = null)
{
if (null === $con)
{
$con = $this->getConnection();
}
$this->updateObject();
$blobData = new BlobData();
$this->saveEmbeddedForms($con);
$this->getObject()->setBlobData($this->getEmbeddedForm('blob_data')->getObject());
$this->getObject()->save($con);
}
Would I need to override saveEmbeddedForms() as well?
Thanks
EDIT:
Ok, so it seems i need to override:
processValues()
I'm just having trouble getting the images width and height attributes.
Does anyone know how I'd do that?
Thanks
If you can get this 2 informations from your blob_data field, you can override the preSave method of your BlobData class which is called just before saving object :
public function preSave($event)
{
//get the information from the blob_data
$this->image_width = ... ;
$this->image_height = ... ;
}
Right, so after all that, I had to override saveEmbeddedForms:
public function saveEmbeddedForms($con = null, $forms = null)
{
if (null === $con)
{
$con = $this->getConnection();
}
if (null === $forms)
{
$photos = $this->getValue('blob_data');
$forms = $this->embeddedForms;
foreach ($this->embeddedForms['blob_data'] as $name => $form)
{
if (!isset($photos[$name]))
{
unset($forms['blob_data'][$name]);
}
}
}
foreach ($forms as $form)
{
if ($form instanceof sfFormObject)
{
$form->saveEmbeddedForms($con);
$blobData = $form->getObject()->getBlobData();
$imageStream = stream_get_contents($blobData);
$image = imagecreatefromstring($imageStream);
$form->getObject()->setImageWidth(imagesx($image));
$form->getObject()->setImageHeight(imagesy($image));
$form->getObject()->setFileExtension('jpg');
//return parent::preSave($con);
$form->getObject()->save($con);
}
else
{
$this->saveEmbeddedForms($con, $form->getEmbeddedForms());
}
}
}
This seemed to work for me
Thanks