PHPstan: Cannot access property $work on array|EntityInterface|null - cakephp

I am developing a web app, trying to keep PHPstan's suggestions in check.
I am having some difficulties with this method:
/**
* AJAX: deletes a work file
*
* #return \Cake\Http\Response|false
*/
public function delete()
{
$this->autoRender = false;
$this->viewBuilder()->setLayout('ajax');
$this->request->allowMethod(['post', 'delete']);
$data = $this->request->getData();
$data = is_array($data) ? $data : [$data];
$workFile = $this->WorkFiles->find('all')
->where(['WorkFiles.id' => $data['id']])
->contain(['Works'])
->first();
$res = [
'status' => 'error',
'message' => __('The file could not be deleted. Please, try again.'),
'class' => 'alert-error',
];
if ($workFile->work->anagraphic_id == $this->authAnagraphics['id']) { // error #1
if ($this->WorkFiles->delete($workFile)) { // error #2
$res = [
'status' => 'success',
'message' => __('File successfully deleted.'),
'class' => 'alert-success',
];
}
}
return $this->response->withStringBody((string)json_encode($res));
}
The code itself works, but I'm having two phpstan errors:
[phpstan] Cannot access property $work on array|Cake\Datasource\EntityInterface|null.
[phpstan] Parameter #1 $entity of method Cake\ORM\Table::delete() expects Cake\Datasource\EntityInterface, array|Cake\Datasource\EntityInterface|null given.
Am I doing something wrong?

Always use inline annotation then here:
/** #var \App\Model\Entity\WorkFile|null $workFile */
$workFile = $this->WorkFiles->find('all')
->where(['WorkFiles.id' => $data['id']])
->contain(['Works'])
->first();
But the comments are right, you are blindly using a possible null value afterwards, as such your code is not written correctly.
Use this instead:
/** #var \App\Model\Entity\WorkFile $workFile */
$workFile = $this->WorkFiles->find('all')
->where(['WorkFiles.id' => $data['id']])
->contain(['Works'])
->firstOrFail();

Related

beforeSave method not working in cakephp3

I have data that I want to modify first before saving it to my database, and so I've researched the beforeSave method.
I have a user's picture input and I want to save its path on my DB after successfully validating it and here's my current code:
src/model/table/UsersTable.php
use Cake\ORM\Entity;
use Cake\Event\Event;
use ArrayObject;
use Cake\Validation\Validator;
public function validationDefault(Validator $validator)
{
$validator
->allowEmptyFile('image_location')
->add('image_location',
[
'mimeType' => [
'rule' => array('mimeType', array( 'image/png', 'image/jpg', 'image/jpeg')),
'message' => 'Please upload images only (png, jpg).'
],
'fileSize' => [
'rule' => array('fileSize', '<=', '10MB'),
'message' => 'Image must be less than 10MB.'
],
]);
return $validator;
}
public function beforeSave($event, $entity, $options)
{
if ($entity->image_location['name']) {
$tmp = $entity->image_location['tmp_name'];
$hash = rand();
$date = data("Ymd");
$image = $dage.$hash;
$target = WWW_ROOT.'img'.DS.'uploads'.DS;
$target = $target.basename($image);
$image_location = "uploads/".$image;
$entity->image_location = $image_location;
move_uploaded_file($tmp, $target);
}
}
The only working part on this is the validation part, but after it successfully validates the image file, the beforeSave method is not working.
What error do I have in my current code or how can I use the beforeSave method in cakephp3.
Thank you very much!
EDIT
I even tried this line:
public function beforeSave($event, $entity, $options)
{
debug($entity);
if ($entity->image_location['name']) {
$tmp = $entity->image_location['tmp_name'];
$hash = rand();
$date = data("Ymd");
$image = $dage.$hash;
$target = WWW_ROOT.'img'.DS.'uploads'.DS;
$target = $target.basename($image);
$image_location = "uploads/".$image;
$entity->image_location = $image_location;
move_uploaded_file($tmp, $target);
}
}
to check the entity the beforeSave method is receiving but, it does not output anything.

Symfony ChoiceType with big array, error 'This value is not valid.'

I have a form with a ChoiceType. Values are set with a Ajax request (this choice depends of an other choice).
But there is many choices (13200), And when I submit the the form whith a correct choice, I have this error "This value is not valid.".
I have tried whith 100 choices, and it's work well.
This form is build whith EventsListener (simplified version) :
$ff = $builder->getFormFactory();
// function to add 'template' choice field dynamically
$func = function ( \Symfony\Component\Form\FormEvent $e) use ($ff, $curlRequest, $builder, $rapport) {
$data = $e->getData();
$form = $e->getForm();
if ($form->has('idsSouscripteur') )
{
$form->remove('idsSouscripteur');
}
$idClient = $data->getIdClient() > 0 ? $data->getIdClient() : null;
$idsSouscripteur = count($data->getIdsSouscripteur()) > 0 ? $data->getIdsSouscripteur() : null;
$souscripteursArray = [];
if (!is_null($idClient)) {
$souscripteurs = /* Request to get 'souscripteurs' objects */;
foreach ($souscripteurs as $souscripteur) {
$souscripteursArray[$souscripteur->nomSouscripteur] = $souscripteur->numInterne;
}
}
$form
->add('idsSouscripteur', ChoiceType::class, [
'label' => 'rapports.block_2.souscripteur',
'mapped' => false,
'multiple' => true,
'choices' => $souscripteursArray,
'constraints' => array(
new NotBlank()
),
'attr' => [
'placeholder' => 'rapports.block_2.souscripteur_placeholder'
]
]);
if (!is_null($idsSouscripteur)) {
$rapport->setIdsSouscripteur($idsSouscripteur);
}
};
// Register the function above as EventListener on PreSet and PreBind
$builder->addEventListener(FormEvents::PRE_SET_DATA, $func);
$builder->addEventListener(FormEvents::PRE_SUBMIT, $func);
Anyone lnow why symfony is not working with big array ?

How to upload file using Cakephp 3.0?

I am trying to create a file upload on cakephp, I haven't been able to find any decent tutorials for cakephp 3.0 that go in detail, and I don't understand how to install plugins.
I have this in my add section
echo $this->Form->create('filename', array('action' => 'upload', 'type' => 'file'));
echo $this->Form->file('filename');
I haven't added anything in the controller yet
/**
* Index method
*
* #return void
*/
public function index()
{
$this->paginate = [
'contain' => ['Courses']
];
$this->set('contents', $this->paginate($this->Contents));
$this->set('_serialize', ['contents']);
}
/**
* View method
*
* #param string|null $id Content id.
* #return void
* #throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$content = $this->Contents->get($id, [
'contain' => ['Courses']
]);
$this->set('content', $content);
$this->set('_serialize', ['content']);
}
/**
* Add method
*
* #return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$content = $this->Contents->newEntity();
if ($this->request->is('post')) {
$content = $this->Contents->patchEntity($content, $this->request->data);
if ($this->Contents->save($content)) {
$this->Flash->success('The content has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The content could not be saved. Please, try again.');
}
}
$courses = $this->Contents->Courses->find('list', ['limit' => 200]);
$this->set(compact('content', 'courses'));
$this->set('_serialize', ['content']);
}
/**
* Edit method
*
* #param string|null $id Content id.
* #return void Redirects on successful edit, renders view otherwise.
* #throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$content = $this->Contents->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$content = $this->Contents->patchEntity($content, $this->request->data);
if ($this->Contents->save($content)) {
$this->Flash->success('The content has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The content could not be saved. Please, try again.');
}
}
$courses = $this->Contents->Courses->find('list', ['limit' => 200]);
$this->set(compact('content', 'courses'));
$this->set('_serialize', ['content']);
}
/**
* Delete method
*
* #param string|null $id Content id.
* #return void Redirects to index.
* #throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$content = $this->Contents->get($id);
if ($this->Contents->delete($content)) {
$this->Flash->success('The content has been deleted.');
} else {
$this->Flash->error('The content could not be deleted. Please, try again.');
}
return $this->redirect(['action' => 'index']);
}
but after this no idea what to do.
First of all, you need to decide on WHEN you're going to handle uploads. I've managed to create a dirty (but working) approach using beforeMarshal method and afterSave method (I'll explain why these two at the end).
If you create your file input like:
<?= $this->Form->file('submittedfile', ['class' => 'form-control input-upload', 'style' => 'height:100px']) ?>
or for hasMany association:
<?= $this->Form->file('images.'.$i.'.submittedfile', ['class' => 'form-control input-upload', 'style' => 'height:100px']) ?>
and you define the right associations:
$this->hasMany('Images', [
'foreignKey' => 'model_id'
]);
you could process those files before the Entity gets patched and saved:
public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options) {
$images = array();
$dir = md5(time().$data['name']);
for ($i = 0; $i < count($data['images']); $i++) {
$image = $data['images'][$i]['submittedfile'];
if (!empty($image['name'])) {
if(!isset($data['id'])) {
$data['temp_dir'] = $dir;
}
else {
$dir = $data['id'];
}
if ($this->Images->uploadFile(array('img', 'model', $dir), $image) === true) {
$images[] = array('name' => pathinfo($image['name'], PATHINFO_FILENAME), 'ext' => pathinfo($image['name'], PATHINFO_EXTENSION));
}
}
}
$data['images'] = $images;
}
This is of course an example. I've decided to check, if there's an ID property set on the Entity (like for edit), because if it's not (like for create), you have to somehow identify the right path.
Here you've got a file uploading function:
public function uploadDir($path = array()) {
return $this->wwwRoot . implode(DS, $path);
}
public function uploadFile($path = array(), $filetoupload = null) {
if (!$filetoupload) {
return false;
}
$dir = new Folder($this->uploadDir($path), true, 755);
$tmp_file = new File($filetoupload['tmp_name']);
if (!$tmp_file->exists()) {
return false;
}
$file = new File($dir->path . DS . $filetoupload['name']);
if (!$tmp_file->copy($dir->pwd() . DS . $filetoupload['name'])) {
return false;
}
$file->close();
$tmp_file->delete();
return true;
}
If you added your images while there was no subdirectory with main entity ID, you have to rename the directory as soon as you get the ID:
public function afterSave(Event $event, Entity $entity, \ArrayObject $options) {
if(!empty($entity->temp_dir)) {
$this->Images->renameFolder(array('img', 'model', $entity->temp_dir),$entity->id);
}
}
calling:
public function renameFolder($path = array(), $newName) {
$oldPath = $this->wwwRoot . implode(DS, $path);
$nameToChange = array_pop($path);
array_push($path, $newName);
$newPath = $this->wwwRoot . implode(DS, $path);
return rename($oldPath, $newPath);
}
Using beforeMarshal you're able to inject your file data into Entity structure before the whole Entity is ready for saving (with associations).
Using afterSave you're able to identify the main object ID and call the set of objects you've uploaded before.
Remember to set recursive rights for saving files onto the directory, as well as rights for creating and renaming directories.

custom datasource find('list') issue

I am creating a custom datasource and I am having problems when i request find('list'). find('all') returns perfectly what I want within my controller but find('list') just returns an empty array.
The funny thing is if I do a die(Debug($results)) in the datasource within the read function then I get my find('list') array correctly but if I return it i then get an empty array in my controller. Any ideas?
Code below:
public function read(Model $model, $queryData = array(), $recursive = null) {
if ($queryData['fields'] == 'COUNT') {
return array(array(array('count' => 1)));
}
$this->modelAlias = $model->alias;
$this->suffix = str_replace('Flexipay', '', $model->alias);
if(empty($model->id)){
$this->url = sprintf('%s%s%s', $this->sourceUrl, 'getAll', Inflector::pluralize($this->suffix));
}
$r = $this->Http->get($this->url, $this->config);
if($r->isOk()){
$results_src = json_decode($r->body, true);
if(is_array($results_src)){
//$this->find('list');
if($model->findQueryType == 'list'){
return $this->findList($queryData, $recursive, $results_src);
}
//$this->find('all');
foreach($results_src['PortalMandantenResponses']['portalMandantenResponses'] as $r){
$results[] = $r;
}
if(!empty($results)){
$e = array($model->alias => $results);
return $e;
}
}
}else{
//
}
return false;
}
My response from die(debug(array($model->alias => $results);
(int) 0 => array(
'Mandant' => array(
'ns2.id' => (int) 79129,
'ns2.name' => 'company a'
)
),
(int) 1 => array(
'Mandant' => array(
'ns2.id' => (int) 70000,
'ns2.name' => 'company b'
)
),
Controller Code is here:
public function test2(){
//$a = $this->User->find('list');
//die(debug($a));
$this->loadModel('Pay.Mandant');
$a = $this->Mandant->find('list', array('fields' => array('ns2.systembenutzernr', 'ns2.systembenutzernrBezeichnung')));
die(debug($a));
}
use,
$a = $this->Mandant->find('list', array('fields' => array('ns2.systembenutzernr', 'ns2.systembenutzernrBezeichnung')));
$this->set(compact('a'));
You can use $a for the dropdown creation in view file.
I just had the same problem writing my custom model though I don't know if the cause in your case is the same, though you should probably look in the same place.
in Model.php there is a function _findList($state, $query, $results), my issue was the fields you specify in the find() call must match the $results structure exactly, otherwise at the end of the _findList() function the call to:
Hash::combine($results, $query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath'])
returns the empty array. The keyPath of {n}.MODELNAME.id, etc must match the name of the model specified in $results, for example
[0] => ['MODELNAME'] = array()
[1] => ['MODELNAME'] = array()
In my case my keyPath and valuePath had a different value for MODELNAME than in the results array
Hope that helps

CakePHP - how to apply translate behavior to existing database?

I have and existing application in CakePHP with a database.
The task is to apply translate behavior to its models. The problem is that i18n.php script just creates _i18n table but doesn't copy existing data to this table.
Don't you know any script that could do that?
Thanks for any help.
I extended the answers from Aziz and MarcoB and created a even more generic CakeShell out of it.
In the method _execute() simply set something like:
$this->_regenerateI18n('BlogPosts', array('title'), 'deu');
And all entries for the Model BlogPosts for the column title in the language deu will be create in the i18n table.
This is CakePHP 2.4 compatible!
<?php
class SetuptranslationsShell extends AppShell {
public function main() {
$selection = $this->in('Start to create translated entries?', array('y', 'n', 'q'), 'y');
if (strtolower($selection) === 'y') {
$this->out('Creating entries in i18n table...');
$this->_execute();
}
}
function _execute() {
$this->_regenerateI18n('BlogPosts', array('title'), 'deu');
$this->_regenerateI18n('BlogTags', array('name'), 'deu');
}
/**
* See http://stackoverflow.com/q/2024407/22470
*
*/
function _regenerateI18n($Model, $fields = array(), $targetLocale) {
$this->out('Create entries for "'.$Model.'":');
if (!isset($this->$Model)) {
$this->{$Model} = ClassRegistry::init($Model);
}
$this->{$Model}->Behaviors->disable('Translate');
$out = $this->{$Model}->find('all', array(
'recursive' => -1,
'order' => $this->{$Model}->primaryKey,
'fields' => array_merge(array($this->{$Model}->primaryKey), $fields))
);
$this->I18nModel = ClassRegistry::init('I18nModel');
$t = 0;
foreach ($out as $v) {
foreach ($fields as $field) {
$data = array(
'locale' => $targetLocale,
'model' => $this->{$Model}->name,
'foreign_key' => $v[$Model][$this->{$Model}->primaryKey],
'field' => $field,
'content' => $v[$Model][$field],
);
$check_data = $data;
unset($check_data['content']);
if (!$this->I18nModel->find('first', array('conditions' => $check_data))) {
if ($this->I18nModel->create($data) AND $this->I18nModel->save($data)) {
echo '.';
$t++;
}
}
}
}
$this->out($t." entries written");
}
}
As far as I know, there's no way to do this. Moreover, because of the way the i18n table is configured to work, I think there's a better solution. A while back, I wrote a patch for the TranslateBehavior that will keep you from having to copy existing data into the i18n table (that felt insanely redundant to me and was a huge barrier to implementing i18n). If no record for that model exists in the i18n table, it will simply read the model record itself as a fallback.
Unfortunately, the Cake team appears to have moved everything to new systems, so I can no longer find either the ticket or the patch that I submitted. My patched copy of the TranslateBehavior is in my Codaset repository at http://codaset.com/robwilkerson/scratchpad/source/master/blob/cakephp/behaviors/translatable.php.
As you might expect, all of the usual warnings apply. The patched file was developed for 1.2.x and works for my needs, by YMMV.
try to use it
function regenerate()
{
$this->Article->Behaviors->disable('Translate');
$out = $this->Article->find('all', array('recursive'=>-1, 'order'=>'id'));
$t = $b = 0;
foreach($out as $v){
$title['locale'] = 'aze';
$title['model'] = 'Article';
$title['foreign_key'] = $v['Article']['id'];
$title['field'] = 'title';
$title['content'] = $v['Article']['title'];
if($this->Article->I18n->create($title) && $this->Article->I18n->save($title)){
$t++;
}
$body['locale'] = 'aze';
$body['model'] = 'Article';
$body['foreign_key'] = $v['Article']['id'];
$body['field'] = 'body';
$body['content'] = $v['Article']['body'];
if($this->Article->I18n->create($body) && $this->Article->I18n->save($body)){
$b++;
}
}
}
Thanks Aziz. I modified your code to use it within the cakeshell
(CakePHP 2.3.8)
function execute() {
$this->out('CORE_PATH: '. CORE_PATH. "\n");
$this->out('CAKEPHP_SHELL: '. CAKEPHP_SHELL. "\n");
$this->out('Migrate BlogPosts');
$this->regenerateI18n('BlogPost', 'title', 'BlogPostI18n');
}
/**
* #param string $Model
* #param string $Field
* #param string $ModelI18n
*/
function regenerateI18n($Model = null, $Field = null, $ModelI18n = null)
{
if(!isset($this->$Model))
$this->$Model = ClassRegistry::init($Model);
if(!isset($this->$ModelI18n))
$this->$ModelI18n = ClassRegistry::init($ModelI18n);
$this->$Model->Behaviors->disable('Translate');
$out = $this->$Model->find('all', array('recursive'=>-1, 'order'=>'id'));
$t = 0;
foreach($out as $v){
$data = array(
'locale' => 'deu',
'model' => $this->$Model->name,
'foreign_key' => $v[$Model]['id'],
'field' => $Field,
'content' => $v[$Model][$Field],
);
if($this->$ModelI18n->create($data) && $this->$ModelI18n->save($data)){
echo '.';
$t++;
}
}
$this->out($t." Entries written");
}

Resources