Determine the toggle state of a toggle command.

@param ToggleCommandInterface $command The toggle command.
@param ModelInterface         $model   The model in scope.

@return bool
775265
private function isTogglerInActiveState($command, $model)
    {
        $dataProvider = $this->environment->getDataProvider($model->getProviderName());
        $propModel    = $model;

        if ($command instanceof TranslatedToggleCommandInterface
            && $dataProvider instanceof MultiLanguageDataProviderInterface
        ) {
            $language = $dataProvider->getCurrentLanguage();
            $dataProvider->setCurrentLanguage($command->getLanguage());
            $propModel = $dataProvider->fetch(
                $dataProvider
                    ->getEmptyConfig()
                    ->setId($model->getId())
                    ->setFields([$command->getToggleProperty()])
            );
            $dataProvider->setCurrentLanguage($language);
        }

        if ($command->isInverse()) {
            return !$propModel->getProperty($command->getToggleProperty());
        }

        return (bool) $propModel->getProperty($command->getToggleProperty());
    }
1094430
private function calculateParameters(CommandInterface $command, $serializedModelId)
    {
        $parameters = (array) $command->getParameters();
        if ($command instanceof ToggleCommandInterface) {
            // Toggle has to trigger the javascript.
            $parameters['act'] = $command->getName();
            $parameters['id']  = $serializedModelId;

            return $parameters;
        }
        if (($command instanceof CutCommandInterface) || ($command instanceof CopyCommandInterface)) {
            // Cut & copy need some special information.
            $parameters        = [];
            $parameters['act'] = $command->getName();

            $inputProvider = $this->environment->getInputProvider();
            // If we have a pid add it, used for mode 4 and all parent -> current views.
            if ($inputProvider->hasParameter('pid')) {
                $parameters['pid'] = $inputProvider->getParameter('pid');
            }

            // Source is the id of the element which should move.
            $parameters['source'] = $serializedModelId;

            return $parameters;
        }

        $extra = (array) $command->getExtra();

        $parameters[($extra['idparam'] ?? null) ?: 'id'] = $serializedModelId;

        return $parameters;
    }
91879
public static function hasCommand($command)
    {
        if (!is_string($command) || strlen($command) < 1) {
            throw new BadMethodCallException('Parameter command is not a valid string');
        }
        $instance = self::getInstance();

        return isset($instance->commands[$command]);
    }
609975
private function doCloneAction(ModelInterface $model)
    {
        $environment = $this->getEnvironment();

        // Make a duplicate.
        $clonedModel = $this->createClonedModel($model);

        // Trigger the pre duplicate event.
        $duplicateEvent = new PreDuplicateModelEvent($environment, $clonedModel, $model);
        $environment->getEventDispatcher()->dispatch($duplicateEvent::NAME, $duplicateEvent);

        // And trigger the post event for it.
        $duplicateEvent = new PostDuplicateModelEvent($environment, $clonedModel, $model);
        $environment->getEventDispatcher()->dispatch($duplicateEvent::NAME, $duplicateEvent);

        return $clonedModel;
    }
291276
protected function parseModel($model, $toggleID)
    {
        $event = new FormatModelLabelEvent($this->environment, $model);
        $this->environment->getEventDispatcher()->dispatch(
            DcGeneralEvents::FORMAT_MODEL_LABEL,
            $event
        );

        $model->setMeta($model::LABEL_VALUE, $event->getLabel());

        $template = $this->getTemplate('dcbe_general_treeview_entry');

        if ($model->getMeta($model::SHOW_CHILDREN)) {
            $toggleTitle = $this->getEnvironment()->getTranslator()->translate('collapseNode', 'MSC');
        } else {
            $toggleTitle = $this->getEnvironment()->getTranslator()->translate('expandNode', 'MSC');
        }

        $toggleUrlEvent = new AddToUrlEvent(
            'ptg=' . $model->getId() . '&amp;provider=' . $model->getProviderName()
        );
        $this->getEnvironment()->getEventDispatcher()->dispatch(ContaoEvents::BACKEND_ADD_TO_URL, $toggleUrlEvent);

        $toggleData = [
            'url'          => \html_entity_decode($toggleUrlEvent->getUrl()),
            'toggler'      => $toggleID,
            'id'           => $model->getId(),
            'providerName' => $model->getProviderName(),
            'level'        => $model->getMeta('dc_gen_tv_level'),
            'mode'         => 6
        ];

        $toggleScript = \sprintf(
            'Backend.getScrollOffset(); return BackendGeneral.loadSubTree(this, %s);',
            \htmlspecialchars(\json_encode($toggleData, JSON_FORCE_OBJECT))
        );

        $this
            ->addToTemplate('theme', Backend::getTheme(), $template)
            ->addToTemplate('environment', $this->getEnvironment(), $template)
            ->addToTemplate('objModel', $model, $template)
            ->addToTemplate('select', $this->isSelectModeActive(), $template)
            ->addToTemplate('intMode', 6, $template)
            ->addToTemplate('strToggleID', $toggleID, $template)
            ->addToTemplate('toggleUrl', $toggleUrlEvent->getUrl(), $template)
            ->addToTemplate('toggleTitle', $toggleTitle, $template)
            ->addToTemplate('toggleScript', $toggleScript, $template)
            ->addToTemplate('selectContainer', $this->getSelectContainer(), $template);

        return $template->parse();
    }
952315
public function run(CommandInterface $command, ConfigurationInterface $configuration)
    {
        if (!$this->shouldBeExecuted($command, $configuration)) {
            return;
        }

        $this->environmentHelper->putEnvs($command->getEnv());

        $this->runPreCommand($command, $configuration);
        $this->runCommand($command, $configuration);
        $this->runPostCommand($command, $configuration);

        $this->environmentHelper->unsetEnvs($command->getEnv());
        $this->environmentHelper->putEnvs($configuration->getEnv());

        if ($configuration->isDebugMode() && !$configuration->getOutput()->confirm('Should install resume?', true)) {
            throw new InstallException('Install aborted...');
        }
    }
757465
protected function validateCommand(CommandInterface $command)
    {
        $this->checkCommandType($command);

        if (!$this->validator instanceof ValidatorInterface) {
            $validatorUnavailableException = new \RuntimeException('Validator is not available');
            $this->logError('Validator service unavailable', $validatorUnavailableException);
            throw $validatorUnavailableException;
        }

        $violationsList = $this->validator->validate($command);

        if (count($violationsList) > 0) {
            throw new InvalidCommandParametersException($violationsList);
        }
    }
859489
public function dispatch(CommandInterface $command, $callback = null){

	    if (!$command->getIdentity() && $this->getDefaultIdentity()) {
            $command->setIdentity($this->getDefaultIdentity());
	    }

	    $service     = $command->getService();
	    $operation   = $command->getOperation();
	    $context     = $command->getContext();
	    $argv        = $command->getParams();
	    $exception = null;

	    if(!$this->exists($command->getService())){
	        throw new ServiceNotFoundException(sprintf(
                'Service "%s" not found', $command->getService()));
	    }

	    $responses = null;

        // Notify, that a (background) job is about to start
        if ($command->getJob()) {
            $jobEvent = $this->createEvent(
                'job.start', $command);

            $this->getEventManager()
                ->trigger($jobEvent);
        }

		// Prepare and trigger init.<service>.<operation> event
		$initEvent = strtolower('init.'.$service.'.'.$operation);

		if(!$this->getEventManager()->getListeners($initEvent)->isEmpty()){
		    $e = $this->createEvent($initEvent, $command);

		    $eventResponses = $this->trigger(
	            $e,
	            function($response){if($response === false) return true;}
		    );

		    if($eventResponses->stopped() && $eventResponses->last() === false){
		        $responses = new ResponseCollection();
		        $responses->setStopped(true);
		    }
		}

		// Dispatch command
		if ($responses === null) {
		    try{
		        $responses = $this->getLoader()->getCommandManager()->trigger(
                    $command,
                    $callback
	            );
		    } catch(\Exception $ex) {
		        $exception = $ex;
		    }
		}

		// Prepare and trigger final.<service>.<operation> event
		$finalEvent = strtolower('final.'.$service.'.'.$operation);

		if(!$this->getEventManager()->getListeners($finalEvent)->isEmpty()){

		    $e = $this->createEvent($finalEvent, $command);

		    // Set exception
		    if ($exception) {
		        $e->setException($exception);
		    }

		    $this->trigger($e);

		    // Listeners have a chance to clear (or change) the exception
		    $exception = $e->getException();
		}

        // Notify that the job has ended
        if ($command->getJob()) {
            $jobEvent = $this->createEvent('job.end', $command);

            if ($exception) {
                $jobEvent->setException($exception);
            }
            $this->trigger($jobEvent);
        }

		// Throw exception if it still exists
		if ($exception instanceof \Exception) {
		    throw $exception;
		}

		return $responses;
	}
662303
public function invokeCommandCallback($method, CommandInterface $command)
    {
        $mixer = $this->getMixer();

        if($mixer instanceof CommandCallbackDelegate) {
            $result = $mixer->invokeCommandCallback($method, $command);
        } else {
            $result = $mixer->$method($command);
        }

        return $result;
    }
269784
public function execute(CommandInterface $command)
    {
        $commandHandler = $this->handlerRepository->getHandler($command);

        if ($commandHandler instanceof CommandExecutorAwareInterface) {
            $commandHandler->setCommandExecutor($this);
        }

        try {
            $result = $commandHandler->handle($command);

            if (!($result instanceof CommandResultInterface)) {
                if (false === $result) {
                    $result = CommandResult::error();
                } else {
                    $result = CommandResult::success();
                }
            }
        } catch (\Exception $e) {
            if ($this->debug) {
                throw $e;
            }

            $result = CommandResult::error(null, [], $e);
        }

        $this->processMessages($command, $result);

        return $result;
    }
1182498
async def toggle(self):
        """"""

        self.logger.debug("toggle command")

        if not self.state == 'ready':
            return

        if self.streamer is None:
            return

        try:
            if self.streamer.is_playing():
                await self.pause()
            else:
                await self.resume()
        except Exception as e:
            logger.error(e)
            pass
603124
protected function setTimeout(CommandInterface $command, array $definition)
    {
        if (isset($definition[static::CONFIG_TIMEOUT])) {
            $command->setTimeout($definition[static::CONFIG_TIMEOUT]);
        }
    }
115479
public static function map(CommandInterface $command) {
        $mapper = new static();
        $mapper->setCommand($command);
        if ($mapper->save() === false) {
            throw new YiiException('Unable to save an instance of \jlorente\command\db\CommandMapper. Errors: [' . Json::encode($mapper->getErrors()) . ']');
        }
    }
339054
public function command($command, $method) {

        self::$commands[] = $command;
        self::$callbacks[$command] = $method;
    }
499025
protected function parseModel($model, $toggleID)
    {
        $model->setMeta($model::LABEL_VALUE, $this->formatModel($model));

        if ($model->getMeta($model::SHOW_CHILDREN)) {
            $toggleTitle = $this->getEnvironment()->getTranslator()->translate('collapseNode', 'MSC');
        } else {
            $toggleTitle = $this->getEnvironment()->getTranslator()->translate('expandNode', 'MSC');
        }

        $toggleScript = \sprintf(
            'Backend.getScrollOffset(); return BackendGeneral.loadSubTree(this, ' .
            '{\'toggler\':\'%s\', \'id\':\'%s\', \'providerName\':\'%s\', \'level\':\'%s\', \'url\':\'%s\'});',
            $toggleID,
            $model->getId(),
            $model->getProviderName(),
            $model->getMeta('dc_gen_tv_level'),
            $this->generateToggleUrl($model)
        );

        $template = new ContaoBackendViewTemplate('widget_treepicker_entry');
        $template
            ->setTranslator($this->getEnvironment()->getTranslator())
            ->set('id', $this->strId)
            ->set('name', $this->strName)
            ->set('theme', Backend::getTheme())
            ->set('fieldType', $this->fieldType)
            ->set('environment', $this->getEnvironment())
            ->set('objModel', $model)
            ->set('strToggleID', $toggleID)
            ->set('toggleUrl', $this->generateToggleUrl($model))
            ->set('toggleTitle', $toggleTitle)
            ->set('toggleScript', $toggleScript)
            ->set('active', static::optionChecked($model->getProperty($this->idProperty), $this->value))
            ->set('idProperty', $this->idProperty);

        $level = $model->getMeta(DCGE::TREE_VIEW_LEVEL);
        if (($this->minLevel > 0) && ($level < ($this->minLevel - 1))) {
            $template->set('fieldType', 'none');
        }
        if (($this->maxLevel > 0) && ($level > ($this->maxLevel - 1))) {
            $template->set('fieldType', 'none');
        }

        return $template->parse();
    }
263931
public function handle(CommandInterface $command)
    {
        $object = $command->getParameter('data');

        if ($command->hasParameter('class')) {
            $class = $command->getParameter('class');
            if (!($object instanceof $class)) {
                return CommandResult::error('invalid_instance');
            }
        }

        try {
            $this->objectManager->flush();
        } catch (ForeignKeyConstraintViolationException $e) {
            return CommandResult::error('constraint_violation');
        }
    }
273585
private function checkExistenceWithCommand(CommandInterface $command)
    {
        try {
            $this->execute($command);
            return true;
        } catch (S3Exception $e) {
            if ($e->getAwsErrorCode() == 'AccessDenied') {
                return true;
            }
            if ($e->getStatusCode() >= 500) {
                throw $e;
            }
            return false;
        }
    }