load external class and member function in Cakephp 3 - cakephp

I'm working on CakePHP 3.2.
I want to import data in bulk from excel file and save them to database. For this I'm using PHPExcel Library.
I have downloaded the library and extracted in vendor directory and thus the filepath to PHPExcel.php is
/vendor/PHPExcel/Classes/PHPExcel.php
and filepath to IOFactory.php is
/vendor/PHPExcel/Classes/PHPExcel/IOFactory.php
I'm including this in my controller like
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
include '../vendor/PHPExcel/Classes/PHPExcel.php';
include '../vendor/PHPExcel/Classes/PHPExcel/IOFactory.php';
/**
* Products Controller
*
* #property \App\Model\Table\ProductsTable $Products
*/
class ProductsController extends AppController
{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
if ($this->Auth->user()['status'] != 1) {
$this->Auth->deny(['sell']);
}
$this->Auth->allow(['bulkUpload']);
}
public function bulkUpload()
{
$inputFileName = $this->request->data('excel_data');
if ($inputFileName != '') {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName); // line 33
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
$highestRow = $objWorksheet->getHighestRow();
for ($row = 2; $row <= $highestRow; ++$row) {
$this->data['Program']['cycle_month'] = $objWorksheet->getCellByColumnAndRow(1, $row)->getValue();
$this->data['Program']['cycle_year'] = $objWorksheet->getCellByColumnAndRow(2, $row)->getValue();
$this->data['Program']['media_partnum'] = $objWorksheet->getCellByColumnAndRow(3, $row)->getValue();
$resultArray[$row-2] = $this->data['Program'];
}
debug($resultArray);
}
}
}
Note : I have never used such plugin and bulk upload that is why I followed code from This Question on StackOverflow
Now, the problem is, When I select a file and upload, it gives error as
Class 'App\Controller\PHPExcel_IOFactory' not found at line 33
I think the problem is with calling PHPExcel_IOFactory class.
PHPExcel_IOFactory class is inside IOFactory.php file
<?php
/** PHPExcel root directory */
if (!defined('PHPEXCEL_ROOT')) {
/**
* #ignore
*/
define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../');
require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
}
class PHPExcel_IOFactory
{
/**
* Search locations
*
* #var array
* #access private
* #static
*/
private static $searchLocations = array(
array( 'type' => 'IWriter', 'path' => 'PHPExcel/Writer/{0}.php', 'class' => 'PHPExcel_Writer_{0}' ),
array( 'type' => 'IReader', 'path' => 'PHPExcel/Reader/{0}.php', 'class' => 'PHPExcel_Reader_{0}' )
);
/**
* Autoresolve classes
*
* #var array
* #access private
* #static
*/
private static $autoResolveClasses = array(
'Excel2007',
'Excel5',
'Excel2003XML',
'OOCalc',
'SYLK',
'Gnumeric',
'HTML',
'CSV',
);
/**
* Private constructor for PHPExcel_IOFactory
*/
private function __construct()
{
}
public static function identify($pFilename)
{
$reader = self::createReaderForFile($pFilename);
$className = get_class($reader);
$classType = explode('_', $className);
unset($reader);
return array_pop($classType);
}
}

I see it's a simple problem of namespaces. Just put a slash before the name class as it is in the global namespace
$inputFileType = \PHPExcel_IOFactory::identify($inputFileName);

You can use composer to load PHPExcel library. It will auto include all classes in your project.
composer require phpoffice/phpexcel
Cheers :)

Related

CakePHP 4.2 Annotate: incorrect app namespace

I'm using CakePHP version 4.2 and am noticing some odd behavior from the annotate script that comes bundled with the API. For one component, the annotate script wants to default to the App\ domain that is CakePHP's default. I've changed the application name so most other classes default to the correct application name. But not this one script and so far, only for this one file.
I've included the body of the component, for review, below. You can see that the #method annotation uses the App\ domain. The trouble comes in when I use PHPStan to analyze my code. If I leave the annotation as is, PHPStan will tell me:
------ --------------------------------------------------------------------------------------------------------------------------------------------------------------
Line src/Controller/Component/CartManagerComponent.php
------ --------------------------------------------------------------------------------------------------------------------------------------------------------------
43 Property Visualize\Controller\Component\CartManagerComponent::$Controller (Visualize\Controller\AppController) does not accept App\Controller\AppController.
44 Call to method loadModel() on an unknown class App\Controller\AppController.
💡 Learn more at https://phpstan.org/user-guide/discovering-symbols
------ --------------------------------------------------------------------------------------------------------------------------------------------------------------
The file itself doesn't use the App\ domain anywhere. I'm not sure where to look for the script to figure out whats wrong. Here is the body of my component in case you see something I do not:
<?php
declare(strict_types=1);
namespace Visualize\Controller\Component;
use Authorization\Identity;
use Cake\Controller\Component;
use Cake\Log\Log;
/**
* CartManager component
*
* #method \App\Controller\AppController getController()
* #property \Visualize\Controller\AppController $Controller
* #property \Visualize\Model\Table\CartsTable $Carts
*/
class CartManagerComponent extends Component
{
/**
* Default configuration.
*
* #var array
*/
protected $_defaultConfig = [];
/**
* #var \Visualize\Controller\AppController
*/
protected $Controller;
/**
* #var \Visualize\Model\Table\CartsTable
*/
protected $Carts;
/**
* #param array $config The current configuration array
* #return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->Controller = $this->getController();
$this->Controller->loadModel('Carts');
}
/**
* Returns the most recent active cart.
*
* #param \Authorization\Identity $user The User entity.
* #return array|\Cake\Datasource\EntityInterface|null
* #noinspection PhpUnnecessaryFullyQualifiedNameInspection
*/
public function getUserCart(Identity $user)
{
$cart = $this->Controller->Carts->newEmptyEntity();
if (!empty($this->Controller->Carts) && is_a($this->Controller->Carts, '\Visualize\Model\Table\CartsTable')) {
$query = $this->Controller->Carts->find('userCart', ['user_id' => $user->getIdentifier()]);
if (!$query->isEmpty()) {
$cart = $query->first();
} else {
$cart->set('user_id', $user->getIdentifier());
$this->Controller->Carts->save($cart);
}
if (is_object($cart) && is_a($cart, '\Cake\Datasource\EntityInterface')) {
$session = $this->Controller->getRequest()->getSession();
$session->write('Cart.id', $cart->id);
}
}
return $cart;
}
/**
* Abandons carts
*
* #param int $user_id The associated user ID
* #param int $cart_id The current cart ID
* #return void
*/
public function pruneCarts(int $user_id, int $cart_id): void
{
if (!empty($this->Controller->Carts) && is_a($this->Controller->Carts, '\Visualize\Model\Table\CartsTable')) {
// Find all the carts we didn't just create:
$userCarts = $this->Controller->Carts->find('all', ['fields' => ['id', 'user_id', 'cart_status']])
->where([
'id !=' => $cart_id,
'user_id' => $user_id,
'cart_status' => 'active',
]);
if (!$userCarts->isEmpty()) {
$count = 0;
foreach ($userCarts as $cart) {
if ($count < 5) {
$record = $this->Controller->Carts->newEmptyEntity();
$record = $this->Controller->Carts->patchEntity($record, $cart->toArray());
$record->set('id', $cart->id);
$record->set('cart_status', ABANDONED_CART);
if (!$this->Controller->Carts->save($record)) {
Log::alert('Error abandoning cart');
}
} else {
$this->Controller->Carts->delete($cart);
}
$count++;
}
}
}
}
}

Mock databases function from drupal 7

I want to create a phpunit test from the following code, but I'm not even sure if it worth it, because the code contains db_update and db_query functions, so, those are database functions and I don't know if it make sense create a test for this, because I don't know if should assume drupal code is working fine.
<?php
namespace Drupal\forum_innovation\Forum;
/**
* Created by PhpStorm.
* User: ldcontreras
* Date: 30/05/18
* Time: 18:26
*/
class ForumCounter implements ForumInterface {
public static function setForumCounter($forum, $uid) {
$counterState = db_update('forum_counter_states')
->fields(array(
'state' => 'read',
))
->condition('uid', $uid)
->condition('tid', $forum)
->execute();
return $counterState;
}
public static function getForumNotification($forum, $uid) {
$unReadNotifications =
db_query('SELECT count(*) as counter
FROM {forum_counter_states} as f WHERE f.uid = :uid AND f.state = :state AND f.tid = :forum',
array(
':uid' => $uid,
':forum' => $forum,
':state' => 'unread'
)
)->fetchAll();
return $unReadNotifications[0]->counter;
}
}
I'm trying to create a test like this, but I need some help and clarification:
<?php
/**
* Created by PhpStorm.
* User: ldcontreras
* Date: 8/06/18
* Time: 10:02
*/
namespace Drupal\forum_innovation\Forum;
class ForumCounterTest extends \PHPUnit_Framework_TestCase {
public function TestSetForumCounter() {
$db_query = $this->getMock('db_update', array('fields', 'condition', 'execute'));
$db_query->expects($this->once())->method('fields')->with($this->equalTo(array(':uid' => 3024));
$db_query->expects($this->once())->method('condition')->with($this->equalTo(array(':uid' => 3024)));
$db_query->expects($this->once())->method('condition')->with($this->equalTo(
array(':tid' => 83))->will(
$this->returnCallback('callback'));
}
}
Thanks!

Fatal error: Declaration of CRMCoreContactController::save($contact) must be compatible with EntityAPIController::save

I recently installed CRM Core and all of its missing modules needed to run it. Sadly I need this module for the project that I am working on but the second I installed them I got this error.
Fatal error: Declaration of CRMCoreContactController::save($contact) must be compatible with EntityAPIController::save($entity, ?DatabaseTransaction $transaction = NULL) in /opt/lampp/htdocs/drupal/modules/crm_core/modules/crm_core_contact/includes/crm_core_contact.controller.inc on line 111
I went back in the code and I couldn't see what to change. Line 111 is the ver last line of the code. Ill paste the code as well maybe someone out there knows how to solve this, please.
<?php
/**
* CRM Contact Entity Class.
*/
class CRMCoreContactEntity extends Entity {
protected function defaultLabel() {
return crm_core_contact_label($this);
}
protected function defaultUri() {
return array(
'path' => 'crm-core/contact/' . $this->identifier(),
'options' => array(
'absolute' => TRUE,
),
);
}
/**
* Method for de-duplicating contacts.
*
* Allows various modules to identify duplicate contact records through
* hook_crm_core_contact_match. This function should implement it's
* own contact matching scheme.
*
* #return array
* Array of matched contact IDs.
*/
public function match() {
$checks = & drupal_static(__FUNCTION__);
$matches = array();
if (!isset($checks->processed)) {
$checks = new stdClass();
$checks->engines = module_implements('crm_core_contact_match');
$checks->processed = 1;
}
// Pass in the contact and the matches array as references.
// This will allow various matching tools to modify the contact
// and the list of matches.
$values = array(
'contact' => &$this,
'matches' => &$matches,
);
foreach ($checks->engines as $module) {
module_invoke($module, 'crm_core_contact_match', $values);
}
// It's up to implementing modules to handle the matching logic.
// Most often, the match to be used should be the one
// at the top of the stack.
return $matches;
}
}
/**
* #file
* Controller class for contacts.
*
* This extends the DrupalDefaultEntityController class, adding required
* special handling for contact objects.
*/
class CRMCoreContactController extends EntityAPIController {
public $revisionKey = 'vid';
public $revisionTable = 'crm_core_contact_revision';
/**
* Create a basic contact object.
*/
public function create(array $values = array()) {
global $user;
$values += array(
'contact_id' => '',
'vid' => '',
'uid' => $user->uid,
'created' => REQUEST_TIME,
'changed' => REQUEST_TIME,
);
return parent::create($values);
}
/**
* Update contact object before saving revision.
*/
protected function saveRevision($entity) {
if (!isset($entity->log)) {
$entity->log = '';
}
$entity->is_new_revision = TRUE;
$entity->uid = $GLOBALS['user']->uid;
return parent::saveRevision($entity);
}
/**
* Updates 'changed' property on save.
*/
public function save($contact) {
$contact->changed = REQUEST_TIME;
// Storing formatted contact label for autocomplete lookups.
$contact->name = crm_core_contact_label($contact);
return parent::save($contact);
}
}
Changing
public function save($contact)
to
public function save($contact, DatabaseTransaction $transaction = NULL)
should work.
You need to switch from PHP 7.x+ to PHP 5.6. This will resolve this error.
Can't give you more advice on how to downgrade without more details on what system you're running but there are many guides out there on this topic.

How to call data from 2 diferent table by id in eloquent?

thats the controller
public function hitung($request, $response, $args)
{
$datauser = User::with(['usia','aktivitas'])->find($args['id']);
$tinggi = $datauser['tinggi'];
$berat = $datauser['berat'];
$nama = $datauser['nama'];
$umur = $datauser['umur'];
$aktivitas = $datauser['aktivitaas_id'];
$usia = $datauser['usia_id'];
$nilai = $datauser->aktivitas->nilai;
$energy = $datauser->usia->energy;
$protein = $datauser->usia->protein;
$lemak = $datauser->usia->lemak;
$karbohidrat = $datauser->usia->karbohidrat;
$amb = 655 + (9.6 * $berat) + (1.8 * $tinggi) - (4.7 * $umur);
$amb = round($amb);
$energytotal = $amb * $nilai + $energy;
$energytotal = round($energytotal);
$protein = (15 * $energytotal / 100) + $protein;
$protein = round($protein);
$lemak = (25 * $energytotal / 100) + $lemak;
$lemak = round($lemak);
$karbohidrat = ($energytotal - ($protein + $lemak)) + $karbohidrat;
$karbohidrat= round($karbohidrat);
return $response ->withJson([
'Nama' => $nama,
'total_energy' => $energytotal ,
'Protein'=> $protein,
'lemak'=> $lemak,
'Karbohidrat'=> $karbohidrat,
]);
}
thats the user model:
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $timestamps = false;
protected $fillable = ['username', 'password', 'nama', 'tinggi', 'berat', 'umur', 'usia_id', 'aktivitas_id'];
protected $table = "users";
public function usia()
{
return $this->belongsTo('App\Models\Usia');
}
public function aktivitas()
{
return $this->belongsTo('App\Models\Aktivitas');
}
public function forum()
{
return $this->hasMany('App\Models\Forum');
}
}
thats the aktivitas model:
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class Aktivitas extends Model
{
protected $table = "aktivitas";
public function user()
{
return $this->hasMany('App\Models\User');
}
}
thats the usia model ,
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class Usia extends Model
{
protected $table = "usia";
public function user()
{
return $this->hasMany('App\Models\User');
}
}
this code is work in local , but when i hosting it , it didnt work , please need help for my exam ...
i think the problem is in this code ,
$datauser = User::with(['usia','aktivitas'])->find($args['id']);
any different way to do it ?
I guess your local is Windows and remote host is Linux
first of all you should know windows file and folder name is not case sensitive and there is no different between Models and models in windows OS
but Linux file and directory name is Case Sensitive
in your codes:
namespace App\models;
and
return $this->hasMany('App\Models\User');
somewhere you use Models and models
you should check directory name and rename it anywhere you write wrong word

CakePHP 2.0 - Use MySQL ENUM field with form helper to create Select Input

I've been researching a bit and I found that CakePHP's form helper doesn't interpret ENUM fields correctly, so it simply outputs a text input. I found a post that suggested to use a helper for that specific purpose. Does anybody know a better way to achieve this? Or if CakePHP devs intend to correct this some day?
Thanks for reading!
Below is one of the helper extention.
App::uses('FormHelper', 'View/Helper');
/**
* APP/View/Helper/MySqlEnumFormHelper.php
* It extends FormHelper to implement ENUM datatype of MySQL.
*
* http://blog.xao.jp/blog/cakephp/implementation-of-mysql-enum-datatype-in-formhelper/
*
* created Oct. 15, 2012
* CakePHP 2.2.3
*/
class MySqlEnumFormHelper extends FormHelper
{
public function input($fieldName, $options = array())
{
if (!isset($options['type']) && !isset($options['options'])) {
$modelKey = $this->model();
if (preg_match(
'/^enum\((.+)\)$/ui',
$this->fieldset[$modelKey]['fields'][$fieldName]['type'],
$m
)) {
$match = trim($m[1]);
$qOpen = substr($match, 0, 1);
$qClose = substr($match, -1);
$delimiter = $qOpen . ',' . $qClose;
preg_match('/^'.$qOpen.'(.+)'.$qClose.'$/u', $match, $m);
$_options = explode($delimiter, $m[1]);
$options['type'] = 'select';
$options['options'] = array_combine($_options, $_options);
}
}
return parent::input($fieldName, $options);
}
}
Cake attempts to be database agnostic and therefore this issue won't be "corrected" since it's not a bug. For example, SQL server doesn't have an exact equivalent of MySQL's ENUM field type.
I would recommend getting your possible list of enum values like so:
YourController.php
// get column type
$type = $this->Model->getColumnType('field');
// extract values in single quotes separated by comma
preg_match_all("/'(.*?)'/", $type, $enums);
// enums
var_dump($enums[1]);
Then use a select field in your view and pass the enums as options. Your current value you'll already have. How does that sound?
I am new to cakephp I found some old code and pieced together an enum select box for you enjoy
/**
* Behavior with useful functionality around models containing an enum type field
*
* Copyright (c) Debuggable, http://debuggable.com
*
*
*
* #package default
* #access public
*
* reworked by Nathanael Mallow for cakephp 2.0
*
*/
/*
*Use case:Add this (EnumerableBehavior.php) to app/Model/Behavior/
* -->in the Model add public $actsAs = array('Enumerable');
* -->in the *_controller add $enumOptions = $this->Categorie->enumOptions('Section');
* -->in the view add print $this->Form->input('{db_field_name}', array('options' => $enumOptions, 'label' => 'here'));
*
*
*/
class EnumerableBehavior extends ModelBehavior {
/**
* Fetches the enum type options for a specific field
*
* #param string $field
* #return void
* #access public
*/
function enumOptions($model, $field) {
//Cache::clear();
$cacheKey = $model->alias . '_' . $field . '_enum_options';
$options = Cache::read($cacheKey);
if (!$options) {
$sql = "SHOW COLUMNS FROM `{$model->useTable}` LIKE '{$field}'";
$enumData = $model->query($sql);
$options = false;
if (!empty($enumData)) {
$enumData = preg_replace("/(enum|set)\('(.+?)'\)/", '\\2', $enumData[0]['COLUMNS']['Type']);
$options = explode("','", $enumData);
}
Cache::write($cacheKey, $options);
}
return $options;
}
}
?>
If you want to use MySqlEnumFormHelper instead of normal and call it by $this->Form-> instead by $this->MySqlEnumFormHelper . You should add this line in your controller to alias MySqlEnumFormHelper as Form.
public $helpers = array('Form' => array(
'className' => 'MySqlEnumForm'
));
/* comments about previus answers ***
Use case:Add this (EnumerableBehavior.php) to app/Model/Behavior/
-->in the Model add public $actsAs = array('Enumerable');
-->in the action of the *_controller add $enumOptions = $this->YourModelName->enumOptions('db_field_name'); $this->set('enumOptions',$enumOptions);
-->in the view add print $this->Form->input('{db_field_name}', array('options' => $enumOptions, 'label' => 'here'));
*
*/
i think the Behaviour way it's good...but the array keys are integer
so i have modified the function like this
function enumOptions($model, $field) {
//Cache::clear();
$cacheKey = $model->alias . '_' . $field . '_enum_options';
$options = Cache::read($cacheKey);
$enumOptions = array();
if (!$options) {
$sql = "SHOW COLUMNS FROM `{$model->useTable}` LIKE '{$field}'";
$enumData = $model->query($sql);
$options = false;
if (!empty($enumData)) {
$enumData = preg_replace("/(enum|set)\('(.+?)'\)/", '\\2', $enumData[0]['COLUMNS']['Type']);
$options = explode("','", $enumData);
foreach ($options as $option) {
$enumOptions["$option"] = $option;
}
}
Cache::write($cacheKey, $enumOptions);
}
return $enumOptions;
}
in order to be able to save the right value in the db field when the form is submitted
I created a function that goes into AppController to handle this. I combined some of the information provided above.
Usage:
$enumList = getEnumValues($ModelField) where ModelField is in this format: 'Model.Field'
Function that I put in AppController:
function getEnumValues($ModelField){
// split input into Model and Fieldname
$m = explode('.', $ModelField);
if ($m[0] == $ModelField) {
return false;
} else {
(! ClassRegistry::isKeySet($m[0])) ? $this->loadModel($m[0]): false;
$type = $this->$m[0]->getColumnType($m[1]);
preg_match_all("/'(.*?)'/", $type, $enums);
foreach ($enums[1] as $value){$enumList[$value] = $value;}
return $enumList;
}
}

Resources