/
Optimization of "c:OnGetConstrainInfo" event [5.2.2-B1]

Optimization of "c:OnGetConstrainInfo" event [5.2.2-B1]

The "c:OnGetConstrainInfo" event looks like this:

/core/units/categories/categories_event_handler.php
/**
 * Returns constrain for priority calculations
 *
 * @param kEvent $event
 * @return void
 * @see PriorityEventHandler
 * @access protected
 */
protected function OnGetConstrainInfo(kEvent $event)
{
   $constrain = ''; // for OnSave

   $event_name = $event->getEventParam('original_event');
   $actual_event_name = $event->getEventParam('actual_event');

   if ( $actual_event_name == 'OnSavePriorityChanges' || $event_name == 'OnAfterItemLoad' || $event_name == 'OnAfterItemDelete' ) {
      $object = $event->getObject();
      /* @var $object kDBItem */

      $constrain = 'ParentId = ' . $object->GetDBField('ParentId');
   }
   elseif ( $actual_event_name == 'OnPreparePriorities' ) {
      $constrain = 'ParentId = ' . $this->Application->GetVar('m_cat_id');
   }
   elseif ( $event_name == 'OnSave' ) {
      $constrain = '';
   }
   else {
      $constrain = 'ParentId = ' . $this->Application->GetVar('m_cat_id');
   }

   $event->setEventParam('constrain_info', Array ($constrain, ''));
}

That might not be obvious at first, but conditions on 2839 and 2845 lines are exactly the same.

Solution

Eliminate code duplication by changing method to look like:

/core/units/categories/categories_event_handler.php
/**
 * Returns constrain for priority calculations
 *
 * @param kEvent $event
 * @return void
 * @see PriorityEventHandler
 * @access protected
 */
protected function OnGetConstrainInfo(kEvent $event)
{
   $constrain = ''; // for OnSave

   $event_name = $event->getEventParam('original_event');
   $actual_event_name = $event->getEventParam('actual_event');

   if ( $actual_event_name == 'OnSavePriorityChanges' || $event_name == 'OnAfterItemLoad' || $event_name == 'OnAfterItemDelete' ) {
      $object = $event->getObject();
      /* @var $object kDBItem */

      $constrain = 'ParentId = ' . $object->GetDBField('ParentId');
   }
   elseif ( $event_name == 'OnSave' ) {
      $constrain = '';
   }
   else {
      $constrain = 'ParentId = ' . $this->Application->GetVar('m_cat_id');
   }

   $event->setEventParam('constrain_info', Array ($constrain, ''));
}

Related Tasks