Write the value of $variable in the current binary stream.

@param \qtism\runtime\common\Variable $variable A QTI Runtime Variable object.
@throws \qtism\runtime\storage\binary\QtiBinaryStreamAccessException
502780
public function writeVariableValue(Variable $variable, $valueType = self::RW_VALUE)
    {
        switch ($valueType) {
            case self::RW_DEFAULTVALUE:
                $getterToCall = 'getDefaultValue';
                break;
                
            case self::RW_CORRECTRESPONSE:
                $getterToCall = 'getCorrectResponse';
                break;
                
            default:
                $getterToCall = 'getValue';
        }
        
        try {
            $value = call_user_func(array($variable, $getterToCall));
            $cardinality = $variable->getCardinality();
            $baseType = $variable->getBaseType();

            if (is_null($value) === true) {
                $this->writeBoolean(true);

                return;
            }

            // Non-null value.
            $this->writeBoolean(false);

            if ($cardinality === Cardinality::RECORD) {
                // is-scalar
                $this->writeBoolean(false);

                // count
                $this->writeShort(count($value));

                // content
                foreach ($value as $k => $v) {
                    $this->writeRecordField(array($k, $v), is_null($v));
                }
            } else {
                $toCall = 'write' . ucfirst(BaseType::getNameByConstant($baseType));

                if ($cardinality === Cardinality::SINGLE) {
                    // is-scalar
                    $this->writeBoolean(true);

                    // content
                    $this->$toCall(($value instanceof QtiScalar) ? $value->getValue() : $value);
                } else {
                    // is-scalar
                    $this->writeBoolean(false);

                    // count
                    $this->writeShort(count($value));

                    // MULTIPLE or ORDERED
                    foreach ($value as $v) {
                        if (is_null($v) === false) {
                            $this->writeBoolean(false);
                            $this->$toCall(($v instanceof QtiScalar) ? $v->getValue() : $v);
                        } else {
                            $this->writeBoolean(true);
                        }
                    }
                }
            }
        } catch (BinaryStreamAccessException $e) {
            $msg = "An error occured while writing a Variable value.";
            throw new QtiBinaryStreamAccessException($msg, $this, QtiBinaryStreamAccessException::VARIABLE, $e);
        }
    }
989417
protected function displayVariable(ApiResource $variable)
    {
        /** @var \Platformsh\Cli\Service\Table $table */
        $table = $this->getService('table');
        /** @var \Platformsh\Cli\Service\PropertyFormatter $formatter */
        $formatter = $this->getService('property_formatter');

        $properties = $variable->getProperties();
        $properties['level'] = $this->getVariableLevel($variable);

        $headings = [];
        $values = [];
        foreach ($properties as $key => $value) {
            $headings[] = new AdaptiveTableCell($key, ['wrap' => false]);
            if ($key === 'value') {
                $value = wordwrap($value, 80, "\n", true);
            }
            $values[] = $formatter->format($value, $key);
        }
        $table->renderSimple($values, $headings);
    }
1031784
public function values($variable)
    {
        foreach ($this->keywordList('VALUES') as $keyword) {
            if ($keyword->subKeys[0] == $variable) {
                return $keyword->values;
            }
        }
        throw new RuntimeException(sprintf('Could not determine values of "%s".', $variable));
    }
783849
public function assign($variable, ZephirVariable $symbolVariable, CompiledExpression $resolvedExpr, CompilationContext $compilationContext, $statement)
    {
        $codePrinter = $compilationContext->codePrinter;

        $variable = $compilationContext->symbolTable->getTempVariable('variable', $compilationContext, $statement);
        $variable->setMustInitNull(true);

        $letStatement = new LetStatement([
            'type' => 'let',
            'assignments' => [
                [
                    'assign-type' => 'variable',
                    'variable' => $variable->getName(),
                    'operator' => 'assign',
                    'expr' => [
                        'type' => $resolvedExpr->getType(),
                        'value' => $resolvedExpr->getCode(),
                        'file' => $statement['file'],
                        'line' => $statement['line'],
                        'char' => $statement['char'],
                    ],
                    'file' => $statement['file'],
                    'line' => $statement['line'],
                    'char' => $statement['char'],
                ],
            ],
        ]);
        $letStatement->compile($compilationContext);

        $symbol = $compilationContext->backend->getVariableCode($symbolVariable);
        $variable = $compilationContext->backend->getVariableCode($variable);

        $codePrinter->output('if (zephir_set_symbol('.$symbol.', '.$variable.' TSRMLS_CC) == FAILURE) {');
        $codePrinter->output("\t".'return;');
        $codePrinter->output('}');
    }
310916
public function assign($variable, $property, ZephirVariable $symbolVariable, CompilationContext $compilationContext, $statement)
    {
        if (!$symbolVariable->isInitialized()) {
            throw new CompilerException("Cannot mutate variable '".$variable."' because it is not initialized", $statement);
        }

        /*
         * Arrays must be stored in the HEAP
         */
        if ($symbolVariable->isLocalOnly()) {
            throw new CompilerException("Cannot mutate variable '".$variable."' because it is local only", $statement);
        }

        if (!$symbolVariable->isInitialized()) {
            throw new CompilerException("Cannot mutate variable '".$variable."' because it is not initialized", $statement);
        }

        /*
         * Only dynamic variables can be used as arrays
         */
        if (!$symbolVariable->isVariable()) {
            throw new CompilerException("Cannot use variable type: '".$symbolVariable->getType()."' as array", $statement);
        }

        if ($symbolVariable->hasAnyDynamicType('unknown')) {
            throw new CompilerException('Cannot use non-initialized variable as an object', $statement);
        }

        /*
         * Trying to use a non-object dynamic variable as object
         */
        if ($symbolVariable->hasDifferentDynamicType(['undefined', 'object', 'null'])) {
            $compilationContext->logger->warning(
                'Possible attempt to increment non-object dynamic variable',
                ['non-object-update', $statement]
            );
        }

        /*
         * Check if the variable to update is defined
         */
        if ('this' == $symbolVariable->getRealName()) {
            $classDefinition = $compilationContext->classDefinition;
            if (!$classDefinition->hasProperty($property)) {
                throw new CompilerException("Class '".$classDefinition->getCompleteName()."' does not have a property called: '".$property."'", $statement);
            }
        } else {
            /*
             * If we know the class related to a variable we could check if the property
             * is defined on that class
             */
            if ($symbolVariable->hasAnyDynamicType('object')) {
                $classType = current($symbolVariable->getClassTypes());
                $compiler = $compilationContext->compiler;

                if ($compiler->isClass($classType)) {
                    $classDefinition = $compiler->getClassDefinition($classType);
                    if (!$classDefinition) {
                        throw new CompilerException('Cannot locate class definition for class: '.$classType, $statement);
                    }

                    if (!$classDefinition->hasProperty($property)) {
                        throw new CompilerException("Class '".$classType."' does not have a property called: '".$property."'", $statement);
                    }
                }
            }
        }

        $compilationContext->headersManager->add('kernel/object');
        $compilationContext->codePrinter->output('RETURN_ON_FAILURE(zephir_property_incr('.$symbolVariable->getName().', SL("'.$property.'") TSRMLS_CC));');
    }
868767
def store_variable(var)
      # Force the correct bounds since we can't explicitly specify binary
      if var.type == :binary
        var.instance_variable_set(:@lower_bound, 0)
        var.instance_variable_set(:@upper_bound, 1)
      end
      set_variable_bounds var.index, var.lower_bound, var.upper_bound, true

      Cbc.Cbc_setObjCoeff @ptr, var.index, var.coefficient
      Cbc.Cbc_setColName(@ptr, var.index, var.name) unless var.name.nil?
      set_variable_type var.index, var.type
    end
246915
public function setVars($variables)
    {
        if (!is_array($variables) && !$variables instanceof ArrayAccess) {
            throw new Exception\InvalidArgumentException(sprintf(
                'Expected array or ArrayAccess object; received "%s"',
                (is_object($variables) ? get_class($variables) : gettype($variables))
            ));
        }

        // Enforce a Variables container
        if (!$variables instanceof Variables) {
            $variablesAsArray = array();
            foreach ($variables as $key => $value) {
                $variablesAsArray[$key] = $value;
            }
            $variables = new Variables($variablesAsArray);
        }

        $this->__vars = $variables;
        return $this;
    }
1136191
public function writeVInt($value)
    {
        // We do not need to check if file position points to the end of "file".
        // Only append operation is supported now

        settype($value, 'integer');
        while ($value > 0x7F) {
            $this->_data .= chr(($value & 0x7F)|0x80);
            $value >>= 7;
        }
        $this->_data .= chr($value);

        $this->_position = strlen($this->_data);
    }
465562
public function markVariableIfUnknown($variable, $type)
    {
        $this->variables[$variable] = $type;
        $this->infered[$variable] = $type;
    }
429788
protected void setVariable(String variableName, Object value, ExecutionEntity sourceExecution, boolean fetchAllVariables) {

    if (fetchAllVariables == true) {

      // If it's in the cache, it's more recent
      if (usedVariablesCache.containsKey(variableName)) {
        updateVariableInstance(usedVariablesCache.get(variableName), value, sourceExecution);
      }

      // If the variable exists on this scope, replace it
      if (hasVariableLocal(variableName)) {
        setVariableLocal(variableName, value, sourceExecution, true);
        return;
      }

      // Otherwise, go up the hierarchy (we're trying to put it as high as possible)
      VariableScopeImpl parentVariableScope = getParentVariableScope();
      if (parentVariableScope != null) {
        if (sourceExecution == null) {
          parentVariableScope.setVariable(variableName, value);
        } else {
          parentVariableScope.setVariable(variableName, value, sourceExecution, true);
        }
        return;
      }

      // We're as high as possible and the variable doesn't exist yet, so
      // we're creating it
      if (sourceExecution != null) {
        createVariableLocal(variableName, value, sourceExecution);
      } else {
        createVariableLocal(variableName, value);
      }

    } else {

      // Check local cache first
      if (usedVariablesCache.containsKey(variableName)) {

        updateVariableInstance(usedVariablesCache.get(variableName), value, sourceExecution);

      } else if (variableInstances != null && variableInstances.containsKey(variableName)) {

        updateVariableInstance(variableInstances.get(variableName), value, sourceExecution);

      } else {

        // Not in local cache, check if defined on this scope
        // Create it if it doesn't exist yet
        VariableInstanceEntity variable = getSpecificVariable(variableName);
        if (variable != null) {
          updateVariableInstance(variable, value, sourceExecution);
          usedVariablesCache.put(variableName, variable);
        } else {

          VariableScopeImpl parent = getParentVariableScope();
          if (parent != null) {
            if (sourceExecution == null) {
              parent.setVariable(variableName, value, fetchAllVariables);
            } else {
              parent.setVariable(variableName, value, sourceExecution, fetchAllVariables);
            }

            return;
          }

          variable = createVariableInstance(variableName, value, sourceExecution);
          usedVariablesCache.put(variableName, variable);

        }

      }

    }

  }
696554
@Override
	public void write(char[] cbuf, int off, int len) throws IOException {
		for (int count = 0; count < len; ++off, ++count) {
			char c = cbuf[off];

			switch (state) {
			case TEXT:
				if (c == '$') {
					state = State.VARIABLE_MARK;
				} else {
					targetWriter.write(c);
				}
				break;

			case VARIABLE_MARK:
				if (c == '{') {
					state = State.VARIABLE;
					variableBuilder.setLength(0);
				} else {
					targetWriter.write('$');
					targetWriter.write(c);
					state = State.TEXT;
				}
				break;

			case VARIABLE:
				if (c == '}') {
					String variable = variables.get(variableBuilder.toString());
					if (variable == null) {
						// if variable not found it should be an internal variable used by processing file
						// for example ${BUILD} from ant files; copy as it is
						targetWriter.write("${");
						targetWriter.write(variableBuilder.toString());
						targetWriter.write('}');
					} else {
						targetWriter.write(variable);
					}
					state = State.TEXT;
				} else {
					variableBuilder.append(c);
				}
				break;

			default:
				throw new IllegalStateException();
			}
		}
	}
1295523
public function assignZval(Variable $variable, $code, CompilationContext $context)
    {
        $code = $this->resolveValue($code, $context);
        if (!$variable->isDoublePointer()) {
            $context->symbolTable->mustGrownStack(true);
            $symbolVariable = $this->getVariableCode($variable);
            $context->codePrinter->output('ZEPHIR_OBS_COPY_OR_DUP('.$symbolVariable.', '.$code.');');
        } else {
            $context->codePrinter->output($variable->getName().' = '.$code.';');
        }
    }
1322066
private void addToUsedVariables(final java.util.List<VariableAndValue> usedVariables, final MethodAndParameter top, final Variable variable) {
        VariableAndValue variableAndValue = new VariableAndValue(variable, top.getParameter());
        if (!usedVariables.contains(variableAndValue)) {
            usedVariables.add(variableAndValue);
        } else {
            int i = 0;
            do {
                i++;
                variableAndValue = new VariableAndValue(
                        new Variable(
                                elementUtils.getName(variable.getName().toString() + i),
                                variable.getType()
                        ),
                        top.getParameter()
                );
            } while (usedVariables.contains(variableAndValue));
            usedVariables.add(variableAndValue);
        }
    }
643997
public function issetVariable($variable)
    {
        // Encrypt the variable-name?
        if (true === $this->hasEncryption()) {
            $variable = $this->encrypt($variable);
        }

        // return the isset status of given variable
        return (true === isset($_SESSION[$variable]));
    }
1251437
public function AddVariable( &$variable )
	{
		$qname = $variable->getQName()->clarkNotation();
		if ( isset( $this->variablesByQName[ $qname ] ) )
		{
			$x = 1;
			\XBRL_Log::getInstance()->formula_validation( "Variable-set", "The variable name (defined on an arc) already exists", array(
				'name' => $qname->clarkNotation(),
				'error' => 'xbrlve:duplicateVariableNames'
			) );
			return false;
		}

		$this->variablesByQName[ $qname ] =& $variable;
		$this->variableLabelToQNameMap[ "{$variable->extendedLinkRoleUri}#{$variable->label}" ] = $qname;

		return true;
	}
1027174
public function addSharedVarReference($name, &$var) {
		if(isset($this->sharedVars[$name])) {
			throw new \Exception('Var with name "' . $name . '" already added');
		}
		$this->sharedVars[$name] =& $var;
	}
86924
public static int setVariable(String varname, String varvalue) throws Exception {
    SessionState ss = SessionState.get();
    if (varvalue.contains("\n")){
      ss.err.println("Warning: Value had a \\n character in it.");
    }
    varname = varname.trim();
    if (varname.startsWith(ENV_PREFIX)){
      ss.err.println("env:* variables can not be set.");
      return 1;
    } else if (varname.startsWith(SYSTEM_PREFIX)){
      String propName = varname.substring(SYSTEM_PREFIX.length());
      System.getProperties().setProperty(propName,
              new VariableSubstitution().substitute(ss.getConf(),varvalue));
    } else if (varname.startsWith(HIVECONF_PREFIX)){
      String propName = varname.substring(HIVECONF_PREFIX.length());
      setConf(varname, propName, varvalue, true);
    } else if (varname.startsWith(HIVEVAR_PREFIX)) {
      String propName = varname.substring(HIVEVAR_PREFIX.length());
      ss.getHiveVariables().put(propName,
              new VariableSubstitution().substitute(ss.getConf(),varvalue));
    } else if (varname.startsWith(METACONF_PREFIX)) {
      String propName = varname.substring(METACONF_PREFIX.length());
      Hive hive = Hive.get(ss.getConf());
      hive.setMetaConf(propName, new VariableSubstitution().substitute(ss.getConf(), varvalue));
    } else {
      setConf(varname, varname, varvalue, true);
    }
    return 0;
  }