Discussion:
[TYPO3-english] Prevent the task from accessing a class repository if there are no records of that class?
christian ewigfrost
2017-11-17 08:51:41 UTC
Permalink
So basically i'm using a Scheduler task in which i first create an object of each class repository and use the function findAll() on each:

/** @var CustomerRepository $apprep2 */
$apprep2 = $objectManager->get(\Cjk\Icingaconfgen\Domain\Repository\ApplianceRepository::class);
/** @var Typo3QuerySettings $querySettings */
$querySettings = $objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);
$apprep2->setDefaultQuerySettings($querySettings);
$appliances = $apprep2->findAll();

Then i use each repository object in a foreach loop to access specific properties of each record in the repository (to write them into a file - but that's another story) like this:

foreach($appliances as $appliance)
{
if($appliance->getKundeuid() == $kunde->getUid())
{

$name = $appliance->getIpv4intern();
$address = $appliance->getIpv4extern();
$file = '/etc/icinga2/conf.d/hosts/'.$kunde->getName().'/Appliance_'. $appliance->getIpv4intern().'_'.$kunde->getKundennummer() . '.conf';

$code_a = 'object Host "';
$code_b = '" {
import "generic-host"
address = "';
$code_c = '"
vars.notification["mail"] = {
groups = [ "icingaadmins" ]
}
}';
$fp = fopen("{$file}", 'wb');
fwrite($fp, $code_a . $name . $code_b . $address . $code_c);
fclose($fp);
}
}

My problem is: The moment i don't have any record of let's say the class "appliance" Typo 3 throws me an error becauuse there is no "appliance" record it wants to access.

"Oops, an error occurred!
Call to a member function getIpv4intern() on null"

Using an if condition like:

"if($appliances != null){...}"

..Still makes the task trying to call "getIpv4intern()"...
What can i do to prevent the task using the foreach loop (or any other part of my code that tries to access the record, if the record is empty?
christian ewigfrost
2017-11-17 11:46:57 UTC
Permalink
I solved the problem myself: Instead of using...

if($appliances != null){...}

I simply checked if a record in the repository is empty:
foreach($appliances as $appliance)
{
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump(!empty($appliance));

if(!empty($appliance)){


if($appliance->getKundeuid() == $kunde->getUid())
{
$name = $appliance->getIpv4intern();
$address = $appliance->getIpv4extern();
$file = '/etc/icinga2/conf.d/hosts/'.$kunde->getName().'/Appliance_'. $appliance->getIpv4intern().'_'.$kunde->getKundennummer() . '.conf';

$code_a = 'object Host "';
$code_b = '" {
import "generic-host"
address = "';
$code_c = '"
vars.notification["mail"] = {
groups = [ "icingaadmins" ]
}
}';
$fp = fopen("{$file}", 'wb');
fwrite($fp, $code_a . $name . $code_b . $address . $code_c);
fclose($fp);
}
}
}

Loading...