Back to AbstractEvent class

Method create

public static static
create
(string $eventName, array $arguments = [])
Creates a new CMS event object for a given event name and subject. The following arguments must be given: subject object The subject of the event. This is the core object you are going to manipulate.
Parameters
  • string $eventName The name of the event, e.g. onTableBeforeLoad
  • array $arguments Additional arguments to pass to the event
Returns
  • static
Since
  • 4.0.0
-
  • \BadMethodCallException If you do not provide a subject argument
Class: AbstractEvent
Project: Joomla

Method create - Source code

/**
 * Creates a new CMS event object for a given event name and subject. The following arguments must be given:
 * subject		object	The subject of the event. This is the core object you are going to manipulate.
 * eventClass	string	The Event class name. If you do not provide it Joomla\CMS\Events\<eventNameWithoutOnPrefix>
 *                      will be used.
 *
 * @param   string  $eventName  The name of the event, e.g. onTableBeforeLoad
 * @param   array   $arguments  Additional arguments to pass to the event
 *
 * @return  static
 *
 * @since   4.0.0
 * @throws  BadMethodCallException  If you do not provide a subject argument
 */
public static function create(string $eventName, array $arguments = [])
{
    // Get the class name from the arguments, if specified
    $eventClassName = '';
    if (isset($arguments['eventClass'])) {
        $eventClassName = $arguments['eventClass'];
        unset($arguments['eventClass']);
    }
    /**
     * If the class name isn't set/found determine it from the event name, e.g. TableBeforeLoadEvent from
     * the onTableBeforeLoad event name.
     */
    if (empty($eventClassName) || !class_exists($eventClassName, true)) {
        $bareName = strpos($eventName, 'on') === 0 ? substr($eventName, 2) : $eventName;
        $parts = Normalise::fromCamelCase($bareName, true);
        $eventClassName = __NAMESPACE__ . '\\' . ucfirst(array_shift($parts)) . '\\';
        $eventClassName .= implode('', $parts);
        $eventClassName .= 'Event';
    }
    // Make sure a non-empty subject argument exists and that it is an object
    if (!isset($arguments['subject']) || empty($arguments['subject']) || !\is_object($arguments['subject'])) {
        throw new BadMethodCallException("No subject given for the {$eventName} event");
    }
    // Create and return the event object
    if (class_exists($eventClassName, true)) {
        return new $eventClassName($eventName, $arguments);
    }
    return new GenericEvent($eventName, $arguments);
}