Apply argument values per definition

@param array $argDef
@param array $argValues

@throws \Exception
768202
protected function applyArguments($argDef, $argValues)
    {
        $storeEnv = $this->getStoreEnv();

        $env = new Environment;
        $env->store = $storeEnv->store;

        $hasVariable = false;
        $args = [];

        foreach ($argDef as $i => $arg) {
            list($name, $default, $isVariable) = $argDef[$i];

            $args[$name] = [$i, $name, $default, $isVariable];
            $hasVariable |= $isVariable;
        }

        $keywordArgs = [];
        $deferredKeywordArgs = [];
        $remaining = [];

        // assign the keyword args
        foreach ((array) $argValues as $arg) {
            if (! empty($arg[0])) {
                if (! isset($args[$arg[0][1]])) {
                    if ($hasVariable) {
                        $deferredKeywordArgs[$arg[0][1]] = $arg[1];
                    } else {
                        $this->throwError("Mixin or function doesn't have an argument named $%s.", $arg[0][1]);
                        break;
                    }
                } elseif ($args[$arg[0][1]][0] < count($remaining)) {
                    $this->throwError("The argument $%s was passed both by position and by name.", $arg[0][1]);
                    break;
                } else {
                    $keywordArgs[$arg[0][1]] = $arg[1];
                }
            } elseif (count($keywordArgs)) {
                $this->throwError('Positional arguments must come before keyword arguments.');
                break;
            } elseif ($arg[2] === true) {
                $val = $this->reduce($arg[1], true);

                if ($val[0] === Type::T_LIST) {
                    foreach ($val[2] as $name => $item) {
                        if (! is_numeric($name)) {
                            $keywordArgs[$name] = $item;
                        } else {
                            $remaining[] = $item;
                        }
                    }
                } elseif ($val[0] === Type::T_MAP) {
                    foreach ($val[1] as $i => $name) {
                        $name = $this->compileStringContent($this->coerceString($name));
                        $item = $val[2][$i];

                        if (! is_numeric($name)) {
                            $keywordArgs[$name] = $item;
                        } else {
                            $remaining[] = $item;
                        }
                    }
                } else {
                    $remaining[] = $val;
                }
            } else {
                $remaining[] = $arg[1];
            }
        }

        foreach ($args as $arg) {
            list($i, $name, $default, $isVariable) = $arg;

            if ($isVariable) {
                $val = [Type::T_LIST, ',', [], $isVariable];

                for ($count = count($remaining); $i < $count; $i++) {
                    $val[2][] = $remaining[$i];
                }

                foreach ($deferredKeywordArgs as $itemName => $item) {
                    $val[2][$itemName] = $item;
                }
            } elseif (isset($remaining[$i])) {
                $val = $remaining[$i];
            } elseif (isset($keywordArgs[$name])) {
                $val = $keywordArgs[$name];
            } elseif (! empty($default)) {
                continue;
            } else {
                $this->throwError("Missing argument $name");
                break;
            }

            $this->set($name, $this->reduce($val, true), true, $env);
        }

        $storeEnv->store = $env->store;

        foreach ($args as $arg) {
            list($i, $name, $default, $isVariable) = $arg;

            if ($isVariable || isset($remaining[$i]) || isset($keywordArgs[$name]) || empty($default)) {
                continue;
            }

            $this->set($name, $this->reduce($default, true), true);
        }
    }
512126
public function error($value, ...$args) {
        return call_user_func_array(
            [__CLASS__, 'event'],
            array_merge([self::ERROR, $value], $args)
        );
    }
946079
private function formatArgs(array $args)
    {
        $result = array();
        foreach ($args as $key => $item) {
            if ('object' === $item[0]) {
                $formattedValue = sprintf("<em>object</em>(%s)", $this->abbrClass($item[1]));
            } elseif ('array' === $item[0]) {
                $formattedValue = sprintf("<em>array</em>(%s)", is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
            } elseif ('string'  === $item[0]) {
                $formattedValue = sprintf("'%s'", htmlspecialchars($item[1], ENT_QUOTES | ENT_SUBSTITUTE, $this->charset));
            } elseif ('null' === $item[0]) {
                $formattedValue = '<em>null</em>';
            } elseif ('boolean' === $item[0]) {
                $formattedValue = '<em>' . strtolower(var_export($item[1], true)) . '</em>';
            } elseif ('resource' === $item[0]) {
                $formattedValue = '<em>resource</em>';
            } else {
                $formattedValue = str_replace("\n", '', var_export(htmlspecialchars((string) $item[1], ENT_QUOTES | ENT_SUBSTITUTE, $this->charset), true));
            }

            $result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
        }

        return implode(', ', $result);
    }
75202
protected function handleArgs(array $args) {
        $groupedArgs = $this->argumentsParser->group($args);
        list($groupedArgs, $continue) = $this->runGlobalCommands($groupedArgs);

        if ($continue === false) {
            return;
        }

        try {
            list($command, $groupedArgs) = $this->argumentsMatcher
                ->matchCommands($this->getNotGlobalCommands(), $groupedArgs);
            $command = clone $command;
            $this->runCommand($command);
        } catch (MissingCommandNameException $ex) {
            array_unshift($args, $this->getDefaultCommandName());
            $this->parseArgs($args);
        } catch (Exception $ex) {
            if ($this->getCatchErrors()) {
                $widget = new ExceptionWidget($this->input, $this->output);
                $widget->render($ex);
            } else {
                throw $ex;
            }
        }
    }
703071
public function addError(...$args) {
        $args = func_get_args();
        if(func_num_args()>2){
            foreach ($args as $error) {
                array_push($this->errors, $error);
            }
        } else {
            if(func_get_args()==1) {
                $this->errors[] = $args[0];
            } else {
                $this->errors[$args[0]] = $args[1];
            }
        }
    }
93536
protected function _call ($command, array $arguments = array(), array $values = null)
    {
        try {
            $this->_connected || $this->connect();
        } catch (\Exception $e) {
            throw $e;
        }

        extract($arguments);

        if (isset($collection_name)) {
            $c = $this->_db->selectCollection($collection_name);
        }

        switch ($command) {
            case 'ensure_index':
                $r = $c->ensureIndex($keys, $options);
                break;
            case 'create_collection':
                $r = $this->_db->createCollection($name, $capped, $size, $max);
                break;
            case 'drop_collection':
                $r = $this->_db->dropCollection($name);
                break;
            case 'command':
                $r = $this->_db->command($values);
                break;
            case 'execute':
                $r = $this->_db->execute($code, $args);
                break;
            case 'batch_insert':
                $r = $c->batchInsert($values);
                break;
            case 'count':
                $r = $c->count($query);
                break;
            case 'find_one':
                $r = $c->findOne($query, $fields);
                break;
            case 'find':
                $r = $c->find($query, $fields);
                break;
            case 'group':
                $r = $c->group($keys, $initial, $reduce, $condition);
                break;
            case 'update':
                $r = $c->update($criteria, $values, $options);
                break;
            case 'insert':
                $r = $c->insert($values, $options);

                return $values;
                break;
            case 'remove':
                $r = $c->remove($criteria, $options);
                break;
            case 'save':
                $r = $c->save($values, $options);
                break;
            case 'get_file':
                $r = $this->gridFS()->findOne($criteria);
                break;
            case 'get_files':
                $r = $this->gridFS()->find($query, $fields);
                break;
            case 'set_file_bytes':
                $r = $this->gridFS()->storeBytes($bytes, $extra, $options);
                break;
            case 'set_file':
                $r = $this->gridFS()->storeFile($filename, $extra, $options);
                break;
            case 'remove_file':
                $r = $this->gridFS()->remove($criteria, $options);
                break;
            case 'aggregate':
                $r = call_user_func_array(array($c, 'aggregate'), $ops);
                break;
        }

        return $r;
    }
265274
protected function apply($function, $args = array())
  {
    foreach ($this->data as $key => &$value) {

      if (!is_array($value)) {
        $value = $this->applyToValue($function, $args, $value);
      } else {
        $value = array_map(function ($v) use ($function, $args) {
          return $this->applyToValue($function, $args, $v);
        }, $value);
      }

    }
  }
493833
public void addProcedureArgument(ProcedureArgumentDef argDef)
    {
        argDef.setOwner(this);
        _procedureArguments.put(argDef.getName(), argDef);
    }
246006
protected static function exclure(&$options, $args = ['type', 'value', 'name'])
    {
        foreach ($options as $key => $option) {
            if (array_has($args, $key)) {
                unset($options[$key]);
            }
        }
    }
1253399
public function parse(array $argv = null)
    {
        $cliArguments = $this->arguments($argv);

        if (in_array('--', $cliArguments)) {
            $cliArguments = $this->removeTrailingArguments($cliArguments);
        }

        $unParsedArguments = $this->prefixedArguments($cliArguments);

        $this->nonPrefixedArguments($unParsedArguments);

        // After parsing find out which arguments were required but not
        // defined on the command line.
        $missingArguments = $this->filter->missing();

        if (count($missingArguments) > 0) {
            throw new InvalidArgumentException(
                'The following arguments are required: '
                . $this->summary->short($missingArguments) . '.'
            );
        }
    }
265931
public function afterUpdate(array &$args) {
        foreach ($this->_affectedRows as $row) {
            foreach ($this->_newValues as $key => $value) {
                // compare the old and new values
                if ($row->$key != $value) {
                    $this->_deleteFile($row->$key);
                }
            }
        }
    }
729096
public function setArgsValues(array $params = null, array $instanceArgs)
    {
        if (is_array($params)) {
            foreach ($params as $param) {
                foreach ($instanceArgs as &$instanceArg) {
                    if (is_null($instanceArg)) {
                        $instanceArg = $param;
                        break;
                    }
                }
            }
        }

        return $instanceArgs;
    }
1290325
function parse($args = null)
    {
        if ($args === null) {
            $args = array_slice($_SERVER['argv'], 1);
        }

        foreach ($args as $pos => $arg) {
            // reset value
            $value = null;

            if (substr($arg, 0, 1) === '-') {
                if (preg_match('/^(.+)=(.+)$/', $arg, $matches)) {
                    $arg = $matches[1];
                    $value = $matches[2];
                }

                if (!$flag = @$this->flags[$arg]) {
                    throw new ParseException(sprintf('Flag "%s" is not defined.', $arg));
                }

                unset($args[$pos]);

                if ($flag->hasValue) {
                    if (!isset($value)) {
                        $value = $args[$pos + 1];
                        unset($args[$pos + 1]);
                    }
                } else {
                    $value = true;
                }

                if (null !== $flag->callback) {
                    call_user_func_array($flag->callback, array(&$value));
                }

                # Set the reference given as the flag's 'var'.
                $flag->var = $this->parsedFlags[$flag->name] = $value;
            }
        }

        # TODO: Refactor this so this fits into the above foreach
        foreach ($this->flags as $flag) {
            if (!array_key_exists($flag->name, $this->parsedFlags)) {
                $flag->var = $this->parsedFlags[$flag->name] = $flag->defaultValue;
            }
        }

        $this->parsedArgs = $args = array_values($args);

        $pos = 0;

        foreach ($this->args as $arg) {
            if ($arg->required and !isset($args[$pos])) {
                throw new ArgumentException(sprintf(
                    'Missing required argument "%s"', $arg->name
                ));
            }

            if (isset($args[$pos])) {
                if ($arg->vararg) {
                    $value = array_slice($args, $pos);
                    $pos += count($value);
                } else {
                    $value = $args[$pos];
                    $pos++;
                }
            } else {
                $value = $arg->defaultValue;
            }

            $this->parsedNamedArgs[$arg->name] = $value;
        }
    }
1316962
protected function normalizeArgs(array $args)
    {
        $args += [
            'resultsPerPage' => null,
            'allowedDownloadFormats' => null,
        ];
        $normalized = [];
        $error = $this->app->make('helper/validation/error');
        /* @var \Concrete\Core\Error\ErrorList\ErrorList $error */
        $valn = $this->app->make('helper/validation/numbers');
        /* @var \Concrete\Core\Utility\Service\Validation\Numbers $valn */
        if ($valn->integer($args['resultsPerPage'], 1)) {
            $normalized['resultsPerPage'] = (int) $args['resultsPerPage'];
        } else {
            $error->add(t('Please specify the number of search results per page.'));
        }
        $allowedDownloadFormats = [];
        if (is_array($args['allowedDownloadFormats'])) {
            $tcProvider = $this->app->make(TranslationsConverterProvider::class);
            foreach (array_unique($args['allowedDownloadFormats']) as $adf) {
                if ($tcProvider->isRegistered($adf) === false) {
                    $error->add(t('Invalid format identifier received'));
                } else {
                    $allowedDownloadFormats[] = $adf;
                }
            }
        }
        $normalized['allowedDownloadFormats'] = implode(',', $allowedDownloadFormats);
        $normalized['allowedDownloadFor'] = (isset($args['allowedDownloadFor']) && is_string($args['allowedDownloadFor'])) ? $args['allowedDownloadFor'] : '';
        if (!array_key_exists($normalized['allowedDownloadFor'], $this->getDownloadAccessLevels())) {
            $error->add(t('Please specify who can download the translations'));
        }
        if (!$error->has()) {
            if ($normalized['allowedDownloadFor'] !== static::ALLOWDOWNLOADFOR_NOBODY && $normalized['allowedDownloadFormats'] === '') {
                $error->add(t('If you specify that some user can download the translations, you should specify the allowed download formats'));
            }
        }

        return $error->has() ? $error : $normalized;
    }
511413
protected function areArgumentsValid($args, array $accepted)
    {
        if ($args == null)
        {
            return;
        }

        foreach ($accepted as $accept)
        {
            if (array_key_exists($accept, $args))
            {
                return true;
            }
        }

        throw new \InvalidArgumentException('This call only accepts these arguments: ' . implode(" | ",$accepted));
    }
673663
public static function call($func, array $args)
    {
        switch ($func) {
            case 'map':
                if (count($args) != 2) throw new \BadMethodCallException("Wrong parameter count for method Func::map");
                return self::map($args[0], $args[1]);
            case 'premap':
                if (count($args) != 2) throw new \BadMethodCallException("Wrong parameter count for method Func::premap");
                return self::premap($args[0], $args[1]);
            case 'to_data':
                if (count($args) != 1) throw new \BadMethodCallException("Wrong parameter count for method Func::to_data");
                return self::to_data($args[0]);
            case 'manipulate':
                if (count($args) != 2) throw new \BadMethodCallException("Wrong parameter count for method Func::manipulate");
                return self::manipulate($args[0], $args[1]);
            default:
                throw new \InvalidArgumentException(sprintf('Unknown function name provided: %s', (string)$func));
        }
    }
1344283
public function processArgs( ICommand &$command, $args )
    {
        $i = 0;

        $ops = array_slice( $args, 2 );

        while ( $i < count( $ops ) )
        {
            $o = $ops[ $i ];

            if ( Option::isShortCode( $o ) || Option::isLongCode( $o ) )
            {
                $option = Command::getOption( $command, $o );

                if ( $option->isRequired )
                {
                    $i++;

                    if ( !Util::validIndex( $i, $ops ) )
                    {
                        throw new CommandException( 'Missing argument for option: ' . $o );
                    }

                    Option::setRequiredValue( $option, $ops[ $i ] );
                }

                if ( $option->isOptional )
                {
                    $value = NULL;

                    if ( $option->type === Type::BOOLEAN )
                    {
                        $value = TRUE;
                    }
                    else
                    {
                        $i++;

                        $value = $ops[ $i ];
                    }

                    if ( Util::validIndex( $i, $ops ) )
                    {
                        Option::setOptionalValue( $option, $value );
                    }
                    else if ( is_bool( $value ) )
                    {
                        Option::setOptionalValue( $option, $value );
                    }
                }
            }

            $i++;
        }
    }