Search for hook functions and run them if defined

@param string $hook_name Name of hook to search for
@param array $args Arguments to pass to the hook function
@throws HookError
@throws BadEntryError
@return mixed Output of hook function
435050
public static function runHook( $hook_name, $args = array() ) {
		global $pgHooks;

		if( !isset( $pgHooks[$hook_name] ) ) return null;

		if( !is_array( $pgHooks[$hook_name] ) ) {
			throw new HookError( "Hook assignment for event `$hook_name` is not an array. Syntax is " . '$pgHooks[\'hookname\'][] = "hook_function";' );
		}

		$method = null;
		foreach( $pgHooks[$hook_name] as $function ){
			if( is_array( $function ) ) {
				if( count( $function ) < 2 ) {
					throw new HookError( "Not enough parameters in array specified for `$hook_name` hook" );
				} elseif( is_object( $function[0] ) ) {
					$object = $function[0];
					$method = $function[1];
					if( count( $function ) > 2 ) {
						$data = $function[2];
					}
				} elseif( is_string( $function[0] ) ) {
					$method = $function[0];
					if( count( $function ) > 1 ) {
						$data = $function[1];
					}
				}

			} elseif( is_string( $function ) ) {
				$method = $function;
			}

			if( isset( $data ) ) {
				$args = array_merge( array( $data ), $args );
			}

			if( isset( $object ) ) {
				$fncarr = array( $object, $method );
			} elseif( is_string( $method ) && in_string( "::", $method ) ) {
				$fncarr = explode( "::", $method );
			} else {
				$fncarr = $method;
			}

			//is_callable( $fncarr ); //Apparently this is a bug. Thanks, MW!

			if( !is_callable( $fncarr ) ) {
				throw new BadEntryError( "MissingFunction", "Hook function $fncarr was not defined" );
			}

			$hookRet = call_user_func_array( $fncarr, $args );

			if( !is_null( $hookRet ) ) return $hookRet;

		}

	}
503041
public function addFilter(string $hook, callable $callable, ...$args)
    {
        return add_filter($this->App->Config->©brand['©var'].'_'.$hook, $callable, ...$args);
    }
1064006
def run_command_hooks(cmd_obj, hook_kind):
    

    hooks = getattr(cmd_obj, hook_kind, None)

    if not hooks:
        return

    for modname, hook in hooks:
        if isinstance(hook, str):
            try:
                hook_obj = resolve_name(hook)
            except ImportError as exc:
                raise DistutilsModuleError(
                    'cannot find hook {0}: {1}'.format(hook, exc))
        else:
            hook_obj = hook

        if not callable(hook_obj):
            raise DistutilsOptionError('hook {0!r} is not callable' % hook)

        log.info('running {0} from {1} for {2} command'.format(
                 hook_kind.rstrip('s'), modname, cmd_obj.get_command_name()))

        try:
            hook_obj(cmd_obj)
        except Exception:
            log.error('{0} command hook {1} raised an exception: %s\n'.format(
                hook_obj.__name__, cmd_obj.get_command_name()))
            log.error(traceback.format_exc())
            sys.exit(1)
105252
def hook(self, *hook_names):
        """"""
        def wrapper(decorated):
            for hook_name in hook_names:
                self.register(hook_name, decorated)
            else:
                self.register(decorated.__name__, decorated)
                if '_' in decorated.__name__:
                    self.register(
                        decorated.__name__.replace('_', '-'), decorated)
            return decorated
        return wrapper
661899
public static function trigger(string $name, ?array $args = null)
  {
    if (!isset(self::$events[$name])) return false;

    foreach (self::$events[$name] as $event => $callback) {
      if (is_callable($callback)) {
        return call_user_func_array($callback, isset($args) ? $args : []);
      }
      else if (is_array($callback)) {
        (new Events)->triggerGroup($callback, $args);
      }
      else if (is_string($callback)) {
        $call = new $callback;
        return call_user_func_array([$call, 'persist'], $args ?? []);
      }
    }
  }
860198
def _run_hooks(self, name, module):
        
        hooks = self.post_load_hooks.pop(name, [])

        for hook in hooks:
            hook(module)
275546
public function callScopeFunction($name, ...$args)
    {
        if (is_string($name) && method_exists($this->model, $method = Str::camel('scope_'.$name))) {
            return $this->model->$method($this, ...$args);
        }

        if (is_callable($name)) {
            return tap($this, function () use ($name) {
                call_user_func($name, $this);
            });
        }

        throw new BadMethodCallException('Scope method could not be resolved: '.$method);
    }
905942
function spawnHook(hookName, args) {
    var stats = fs.statSync(hookName);
    var command = hookName;
    var opts = args;
    var hook;

    if (isWin32) {
        hook = fs.readFileSync(hookName).toString();
        if (!require('shebang-regex').test(hook)) {
            throw new Error('Cannot find shebang in hook: ' + hookName + '.');
        }
        command = require('shebang-command')(require('shebang-regex').exec(hook)[0]);
        opts = [hookName].concat(opts);
        if (command === 'node') {
            command = 'node.exe';
        }
    } else if (!(stats && stats.isFile() && isExecutable(stats))) {
        throw new Error('Cannot execute hook: ' + hookName + '. Please check file permissions.');
    }
    return spawn(command, opts, {stdio: 'inherit'});
}
1083135
public static function runHook($name, array $params = [ ])
    {
        static::ensureHookPoint($name);

        foreach (static::$hooks[ $name ] as $handler) {
            if ($handler instanceof \Closure) {

                call_user_func_array($handler, $params);
            } elseif (class_exists($handler)) {
                $instance = app()->make($handler);

                call_user_func_array([ $instance, 'handle' ], $params);
            }
        }
    }
693105
def execute_hook(self, event_name):
        """"""
        hook = self.settings.hooks.get_string('{!s}'.format(event_name))
        if hook is not None and hook != "":
            hook = hook.split()
            try:
                subprocess.Popen(hook)
            except OSError as oserr:
                if oserr.errno == 8:
                    log.error("Hook execution failed! Check shebang at first line of %s!", hook)
                    log.debug(traceback.format_exc())
                else:
                    log.error(str(oserr))
            except Exception as e:
                log.error("hook execution failed! %s", e)
                log.debug(traceback.format_exc())
            else:
                log.debug("hook on event %s has been executed", event_name)
1080444
def subset_hook_caller(self, name, remove_plugins):
        
        orig = getattr(self.hook, name)
        plugins_to_remove = [plug for plug in remove_plugins if hasattr(plug, name)]
        if plugins_to_remove:
            hc = _HookCaller(
                orig.name, orig._hookexec, orig.spec.namespace, orig.spec.opts
            )
            for hookimpl in orig.get_hookimpls():
                plugin = hookimpl.plugin
                if plugin not in plugins_to_remove:
                    hc._add_hookimpl(hookimpl)
                    # we also keep track of this hook caller so it
                    # gets properly removed on plugin unregistration
                    self._plugin2hookcallers.setdefault(plugin, []).append(hc)
            return hc
        return orig
1309854
public function exec_hook($hook, $args = array())
    {
        if (!is_array($args)) {
            $args = array('arg' => $args);
        }

        // TODO: avoid recursion by checking in_array($hook, $this->exec_stack) ?

        $args += array('abort' => false);
        array_push($this->exec_stack, $hook);

        // Use for loop here, so handlers added in the hook will be executed too
        if (!empty($this->handlers[$hook])) {
            for ($i = 0; $i < count($this->handlers[$hook]); $i++) {
                $ret = call_user_func($this->handlers[$hook][$i], $args);
                if ($ret && is_array($ret)) {
                    $args = $ret + $args;
                }

                if ($args['break']) {
                    break;
                }
            }
        }

        array_pop($this->exec_stack);
        return $args;
    }
643684
def generate_hooked_command(cmd_name, cmd_cls, hooks):
    

    def run(self, orig_run=cmd_cls.run):
        self.run_command_hooks('pre_hooks')
        orig_run(self)
        self.run_command_hooks('post_hooks')

    return type(cmd_name, (cmd_cls, object),
                {'run': run, 'run_command_hooks': run_command_hooks,
                 'pre_hooks': hooks.get('pre', []),
                 'post_hooks': hooks.get('post', [])})
1132977
protected function loaderHooks($instance,$hook_name,$class='',$method_name='',$data=array())
    {
        $hooks = configItem('hooks');

        if(isset($hooks[$hook_name]) && $hooks[$hook_name]['active'])
        {
            $ns         = "\\application\\".$hooks[$hook_name]['namespace'];
            $hook_class = $hooks[$hook_name]['class'];
            $class_ns   = "$ns\\$hook_class";

            $hook_instance = new $class_ns();
            if($hook_name == 'pre_template')
            {
                $para = array($instance,$class,$method_name,$data);
            }
            else
            {
                $para = array($instance,$data);
            }
            call_user_func_array(array($hook_instance, $hooks[$hook_name]['method']), $para);
        }

    }
1288478
public function hook($hook_spot, $arg = null)
    {
        if (is_null($arg)) {
            $arg = [];
        } elseif (!is_array($arg)) {
            throw new Exception([
                'Arguments for callbacks should be passed as array',
                'arg' => $arg,
            ]);
        }

        $return = [];

        try {
            if (
                isset($this->hooks[$hook_spot])
                && is_array($this->hooks[$hook_spot])
            ) {
                krsort($this->hooks[$hook_spot]); // lower priority is called sooner
                $hook_backup = $this->hooks[$hook_spot];
                while ($_data = array_pop($this->hooks[$hook_spot])) {
                    foreach ($_data as &$data) {
                        $return[] = call_user_func_array(
                            $data[0],
                            array_merge(
                                [$this],
                                $arg,
                                $data[1]
                            )
                        );
                    }
                }

                $this->hooks[$hook_spot] = $hook_backup;
            }
        } catch (HookBreaker $e) {
            $this->hooks[$hook_spot] = $hook_backup;

            return $e->return_value;
        }

        return $return;
    }
555798
protected function invokeCommand($command_name, array $args = []) {
    $this->invokeDepth++;

    if (!$this->isCommandDisabled($command_name)) {
      /** @var \Acquia\Blt\Robo\Application $application */
      $application = $this->getContainer()->get('application');
      $command = $application->find($command_name);

      $input = new ArrayInput($args);
      $input->setInteractive($this->input()->isInteractive());
      $prefix = str_repeat(">", $this->invokeDepth);
      $this->output->writeln("<comment>$prefix $command_name</comment>");
      $exit_code = $application->runCommand($command, $input, $this->output());
      $this->invokeDepth--;

      // The application will catch any exceptions thrown in the executed
      // command. We must check the exit code and throw our own exception. This
      // obviates the need to check the exit code of every invoked command.
      if ($exit_code) {
        throw new BltException("Command `$command_name {$input->__toString()}` exited with code $exit_code.");
      }
    }
  }
831083
public function run($hook, $args = null)
    {
        if (is_array($args)) {
            $this->doActionRefArray($hook, $args);
        } else {
            $this->doAction($hook, $args);
        }

        return $this;
    }