Шаблон класса компонента
<?php
/**
* This file is part of the Studio Fact package.
* @package citfact
* @copyright 2017 Studio Fact
*/
use Bitrix\Main;
use Bitrix\Main\Application;
use Bitrix\Main\Localization\Loc;
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) die();
class CitfactMyComponent extends CBitrixComponent
{
/**
* Fatal error list.
* @var string[] Array of fatal errors.
*/
protected $errorsFatal = [];
/**
* Non-fatal error list.
* @var string[] Array of non-fatal errors.
*/
protected $errorsNonFatal = [];
public function __construct($component = null)
{
parent::__construct($component);
Loc::loadMessages(__FILE__);
}
/**
* Function checks and prepares all the parameters passed. Everything about $arParam modification is here.
* @param mixed[] $arParams List of unchecked parameters
* @return mixed[] Checked and valid parameters
*/
public function onPrepareComponentParams($arParams)
{
$this->tryParseInt($arParams['PARAM1'], 30);
$this->tryParseString($arParams['PARAM2'], 'deafult');
return $arParams;
}
/**
* Prepare all required data.
* @return void
* @throws User\Exception\NotFoundException
*/
protected function prepareData()
{
}
/**
* Move data to $arResult
* @return void
*/
protected function makeResult()
{
$arResult = [];
$this->arResult = $arResult;
}
/**
* Function implements all the life cycle of our component
* @return void
*/
public function executeComponent()
{
try {
$this->setFrameMode(false);
$this->prepareData();
$this->makeResult();
} catch (Exception $e) {
$this->errorsFatal[$e->getCode()] = $e->getMessage();
}
$this->formatResultErrors();
$this->includeComponentTemplate();
}
/**
* Move all errors to $arResult, if there were any
* @return void
*/
protected function formatResultErrors()
{
$errors = array();
if (!empty($this->errorsFatal))
$errors['FATAL'] = $this->errorsFatal;
if (!empty($this->errorsNonFatal))
$errors['NONFATAL'] = $this->errorsNonFatal;
if (!empty($errors))
$this->arResult['ERRORS'] = $errors;
// backward compatiblity
$error = each($this->errorsFatal);
if (!empty($error['value']))
$this->arResult['ERROR_MESSAGE'] = $error['value'];
}
/**
* Function reduces input value to integer type, and, if gets null, passes the default value
* @param mixed $fld Field value
* @param int $default Default value
* @param int $allowZero Allows zero-value of the parameter
* @return int Parsed value
*/
public static function tryParseInt(&$fld, $default, $allowZero = null)
{
$fld = intval($fld);
if(!$allowZero && !$fld && isset($default))
$fld = $default;
return $fld;
}
/**
* Function processes string value and, if gets null, passes the default value to it
* @param mixed $fld Field value
* @param string $default Default value
* @return string parsed value
*/
public static function tryParseString(&$fld, $default)
{
$fld = trim((string)$fld);
if(!strlen($fld) && isset($default))
$fld = htmlspecialcharsbx($default);
return $fld;
}
}