Make property set code

@param array $property_injections

@return string

@throws CompileErrorException
324907
private function propertySetList(array $property_injections)
    {
        $this->state->category = CompilerState::CATEGORY_PROPERTY;
        $ret = '';
        foreach($property_injections as $injection){
            $property_name = $injection['property'] ?? null;
            $value = $injection['value'] ?? null;
    
            $this->state->name = $property_name;
    
            if (is_null($value)){
                $value = 'null';
            }
            elseif (is_string($value)){
                $value = $this->decorateStringValue($value);
            }
            elseif (is_array($value)){
                $value = $this->decorateArrayValue($value);
            }
            
            $ret .= "        \$component->{$property_name} = {$value};\n";
        }
        return $ret;
    }
669709
private function compileUnitTypes()
    {
        $code = '';
        
        foreach ($this->unitTypes as $unitType) {
            $code .= sprintf("'%s' => %s,",$unitType->getType(),var_export($unitType->toArray(),true));
        }

        return $code;
    }
869046
protected function buildPropertyWriters()
    {
        $body = '';

        foreach ($this->propertyWriters as $propertyWriter) {
            $property = $propertyWriter->getOriginalProperty();
            $propertyName = $property->getName();

            $body .= $this->buildExtractProperty(
                '%s => $data["\\0%s\\0%s"],',
                [
                    var_export($propertyName, true),
                    $property->getDeclaringClass()->getName(),
                    $propertyName,
                ]
            );
        }

        return $body;
    }
473658
public function getVariableFromMaps($var, TransientVarsInterface $transientVars, PropertySetInterface $ps)
    {
        $firstDot = strpos($var, '.');
        $actualVar = $var;

        if (false !== $firstDot) {
            $actualVar = substr($var, 0, $firstDot);
        }


        $o = null;
        if ($transientVars->offsetExists($actualVar)) {
            $o = $transientVars->offsetGet($actualVar);
        }

        if (null === $o) {
            $o = $ps->getAsActualType($actualVar);
        }

        if (false !== $firstDot) {
            $property = substr($var, $firstDot + 1);
            $o = $this->getPropertyObject($o, $property);
        }

        return $o;
    }
411674
final private function prepareData($properties) {
	
		// trigger before preparing data
		$this->beforePrepareData();
		
		// properly cast a property of this object and return it
		$cast = function($prop) {
			
			$field = static::getMappedField($prop);

			switch ($this->getPropertyType($prop)) {
				
				// integer or bool will cast to integer
				case 'int':
				case 'bool':
					if (is_null($this->$prop) and static::isNullable($field)) {
						$ret = NULL;
					} else {
						$ret = (int)$this->$prop;
					}
					break;
				
				// should be DateTime, maybe null
				case 'DateTime':
					if (is_a($this->$prop, 'DateTime')) {
						$dt = clone($this->$prop);
						$dt->setTimezone(new \DateTimeZone(BASE_TIMEZONE));
						$ret = $dt->format('Y-m-d H:i:s');
					} else if (static::isNullable($field)) {
						$ret = NULL;
					} else {
						$field = static::getColumnType($field);
						$ret = 'date' == $field->type ? '0000-00-00' :'0000-00-00 00:00:00';
					}
					break;
						
				// join array strings in CSV format 
				case 'csv':
					$ret = implode(',', array_filter((array)$this->$prop));
					break;
					
				case 'float':
					if (is_null($this->$prop) and static::isNullable($field)) {
						$ret = NULL;
					} else {
						$curr = setlocale(LC_NUMERIC, 0);
						setlocale(LC_NUMERIC, 'en_US');
						$ret = (string)$this->$prop;
						setlocale(LC_NUMERIC, $curr);
					}
					break;

				// assign with no convertion
				default:
					if ((is_null($this->$prop) or (''==$this->$prop and !static::isEmptiable($field)))
							and static::isNullable($field)) {
						$ret = NULL;
					} else {
						$ret = $this->$prop;
					}
					break;
					
			}
			
			return $ret;
			
		};
		
		// force to array
		$properties	= (array)$properties;

		$class = get_called_class();
		$binds = $class::getBinds();
		
		// create the return object
		$dbObj = new \stdClass();
		
		foreach ($properties as $prop) {
			if (array_key_exists($prop, $binds)) {
				$dbObj->{$binds[$prop]} = $cast($prop);
			}
		}
		
		// trigger after prepared data
		$this->afterPrepareData($dbObj);
			
		return $dbObj;
	
	}
267095
private function makePluginsCode()
    {
        if($this->sCssCode === null || $this->sJsCode === null || $this->sJsReady === null)
        {
            $this->sCssCode = '';
            $this->sJsCode = '';
            $this->sJsReady = '';
            foreach($this->xPluginManager->getResponsePlugins() as $xResponsePlugin)
            {
                if(($sCssCode = trim($xResponsePlugin->getCss())))
                {
                    $this->sCssCode .= rtrim($sCssCode, " \n") . "\n";
                }
                if(($sJsCode = trim($xResponsePlugin->getJs())))
                {
                    $this->sJsCode .= rtrim($sJsCode, " \n") . "\n";
                }
                if(($sJsReady = trim($xResponsePlugin->getScript())))
                {
                    $this->sJsReady .= trim($sJsReady, " \n") . "\n";
                }
            }

            $this->sJsReady = $this->render('jaxon::plugins/ready.js', ['sPluginScript' => $this->sJsReady]);
            foreach($this->xPluginManager->getRequestPlugins() as $xRequestPlugin)
            {
                if(($sJsReady = trim($xRequestPlugin->getScript())))
                {
                    $this->sJsReady .= trim($sJsReady, " \n") . "\n";
                }
            }

            foreach($this->xPluginManager->getPackages() as $sPackageClass)
            {
                $xPackage = jaxon()->di()->get($sPackageClass);
                if(($sCssCode = trim($xPackage->css())))
                {
                    $this->sCssCode .= rtrim($sCssCode, " \n") . "\n";
                }
                if(($sJsCode = trim($xPackage->js())))
                {
                    $this->sJsCode .= rtrim($sJsCode, " \n") . "\n";
                }
                if(($sJsReady = trim($xPackage->ready())))
                {
                    $this->sJsReady .= trim($sJsReady, " \n") . "\n";
                }
            }
        }
    }
146582
public function serialize_properties()
    {
        if (!empty($this->serialized_properties)) {
            return $this->serialized_properties;
        }

        $shift = 15;
        $flag_bits = 0;
        $flags = array();
        $raw_bytes = new AMQPWriter();

        foreach ($this->prop_types as $key => $prototype) {
            $val = isset($this->properties[$key]) ? $this->properties[$key] : null;

            // Very important: PHP type eval is weak, use the === to test the
            // value content. Zero or false value should not be removed
            if ($val === null) {
                $shift -= 1;
                continue;
            }

            if ($shift === 0) {
                $flags[] = $flag_bits;
                $flag_bits = 0;
                $shift = 15;
            }

            $flag_bits |= (1 << $shift);
            if ($prototype != 'bit') {
                $raw_bytes->{'write_' . $prototype}($val);
            }

            $shift -= 1;
        }

        $flags[] = $flag_bits;
        $result = new AMQPWriter();
        foreach ($flags as $flag_bits) {
            $result->write_short($flag_bits);
        }

        $result->write($raw_bytes->getvalue());

        $this->serialized_properties = $result->getvalue();

        return $this->serialized_properties;
    }
25281
private <T> T injectSetters(T r, JSONObject j, Collection<String> exclusions) {
        // try to assign rest of the properties
        OUTER:
        for (String key : (Set<String>)j.keySet()) {
            if (!exclusions.contains(key)) {
                try {
                    // try field injection first
                    for (Class c=r.getClass(); c!=null; c=c.getSuperclass()) {
                        try {
                            Field f = c.getDeclaredField(key);
                            if (f.getAnnotation(DataBoundSetter.class)!=null) {
                                f.setAccessible(true);
                                f.set(r, bindJSON(f.getGenericType(), f.getType(), j.get(key)));
                                continue OUTER;
                            }
                        } catch (NoSuchFieldException e) {
                            // recurse into parents
                        }
                    }

                    Method wm = findDataBoundSetter(r.getClass(), key);
                    if (wm==null)   continue;

                    Class<?>[] pt = wm.getParameterTypes();
                    assert pt.length==1;

                    // only invoking public methods for security reasons
                    wm.invoke(r, bindJSON(wm.getGenericParameterTypes()[0], pt[0], j.get(key)));
                } catch (IllegalAccessException e) {
                    LOGGER.log(WARNING, "Cannot access property " + key + " of " + r.getClass(), e);
                } catch (InvocationTargetException e) {
                    LOGGER.log(WARNING, "Cannot access property " + key + " of " + r.getClass(), e);
                }
            }
        }

        invokePostConstruct(getWebApp().getMetaClass(r).getPostConstructMethods(), r);

        return r;
    }
192610
public function withProperties(array $properties): self
    {
        $map = $this->properties;

        foreach ($properties as $key => $value) {
            $map = $map->put($key, $value);
        }

        return new self(
            $this->class,
            $map,
            $this->injectionStrategy,
            $this->instanciator
        );
    }
1271528
private function findPropertyInjections(array $injections)
    {
        $ret = [];
        if (is_array($injections)) {
            foreach ($injections as $injection) {
                if (!isset($injection['property'])){
                    continue;
                }
                $ret[] = $injection;
            }
        }
        return $ret;
    }
778478
public function setProperties(array $properties = [])
    {
        foreach ($properties as $property => $value) {
            $method = 'set'.ucfirst($property);
            if (!method_exists($this, $method)) {
                throw new \RuntimeException("Undefined method $method.");
            }

            if (!in_array($property, $this->validProperties)) {
                throw new \Exception('You are trying to set invalid properties. Please check valid properties.');
            }

            $this->{$method}($value);
        }
    }
894804
protected function generateProperty($propertyName, array $data, $directory, array $dataTypes)
    {
        $property = $this->getPropertyClassName($propertyName);

        $class = new PhpClass();
        $class
            ->setQualifiedName('SecIT\\SchemaOrg\\Mapping\\Property\\'.$property)
            ->setParentClassName('AbstractProperty')
            ->setDescription($property.' class.'."\n\n".'@method '.$property.' setValue($value)')
            ->setMethod(PhpMethod::create('getSchemaUrl')
                ->setDescription('Get schema URL.')
                ->setType('string')
                ->setBody('return \''.$data['url'].'\';')
            )
        ;

        if ($this->backwardCompatibility && !$this->php7ClassNames) {
            $this->php7ClassNames = true;
            $deprecatedMessage = 'This class is deprecated and will be removed in release 3.4. Use SecIT\\SchemaOrg\\Mapping\\Property\\'.$this->getPropertyClassName($propertyName).' instead.';
            $this->php7ClassNames = false;
            $class->setDescription($class->getDescription()."\n\n".'@deprecated '.$deprecatedMessage);
        }

        $instanceCheckConditions = [];
        foreach ($data['ranges'] as $range) {
            if (isset($dataTypes[$range])) {
                $class->addUseStatement('SecIT\\SchemaOrg\\Mapping\\DataType');
                $instanceCheckConditions[] = '$value instanceof DataType\\'.$this->getDataTypeClassName($range);
            } else {
                $class->addUseStatement('SecIT\\SchemaOrg\\Mapping\\Type');
                $instanceCheckConditions[] = '$value instanceof Type\\'.$this->getTypeClassName($range);
            }
        }

        // if no conditions than always return true
        if (!$instanceCheckConditions) {
            $instanceCheckConditions[] = 'true';
        }

        $class
            ->setMethod(PhpMethod::create('isValueValid')
                ->setDescription('Check is value valid.')
                ->addParameter(PhpParameter::create('value')
                    ->setType('string')
                )
                ->setType('bool')
                ->setBody('return '.implode(' || ', $instanceCheckConditions).';')
            )
        ;

        $generator = new CodeGenerator();
        $code = $generator->generate($class);

        file_put_contents($directory.$property.'.php', "<?php\n\n".$code);
    }
448135
private function getUnsettablePropertiesDeclaration()
    {

        // if unsettable properties are the default we don't need to do anything
        if( $this->unsetableProperties === array('id') ) {
            return array();
        }

        $unsetableProperties = array_map(
            function($property){
                return "'".addslashes($property)."'";
            }
            , $this->unsetableProperties
        );

        $this->class->classComponents[] = new VariableDeclaration(
            'unsetableProperties',
            new Sformatf( <<<'PHP'
                /**
                 * Unsetable properties
                 * @var array
                 */
                protected static $unsetableProperties = [%s];
PHP
                , implode( ', ', $unsetableProperties )
            )
        );

        return $this;

    }
1016284
private function getAutocodeProperties()
    {
        $r = '';

        $autocode = (array)$this->xml->xpath('/draggy/autocode');
        $autocode = (array)$autocode[0];

        $autocodeProperties     = (array)$autocode['properties'];
        $autocodeConfigurations = (array)$autocode['configurations'];
        $autocodeTemplates      = (array)$autocode['templates'];

        foreach ($autocodeProperties as $propertyName => $propertyValue) {
            $r .= 'Autocode.prototype.setProperty(\'' . $propertyName . '\', true === ' . $propertyValue  . ');' . PHP_EOL;
        }

        foreach ($autocodeConfigurations as $configurationName => $configurationValue) {
            $r .= 'Autocode.prototype.setConfiguration(\'' . $configurationName . '\', \'' . str_replace('\\', '\\\\', $configurationValue)  . '\');' . PHP_EOL;
        }

        foreach ($autocodeTemplates as $templateName => $templateValue) {
            $r .= 'Autocode.prototype.setTemplate(\'' . $templateName . '\', "' . str_replace('\\', '\\\\', $templateValue) . '");' . PHP_EOL;
        }

        return $r;
    }
323416
public function prepareBindings(array $bindings)
    {
        $grammar = $this->getQueryGrammar();

        $prepared = array();

        foreach ($bindings as $key => $binding)
        {
            // The bindings are collected in a little bit different way than
            // Eloquent, we will need the key name in order to know where to replace
            // the value using the Neo4j client.
            $value = $binding;

            // We need to get the array value of the binding
            // if it were mapped
            if (is_array($value))
            {
                // There are different ways to handle multiple
                // bindings vs. single bindings as values.
                $value = array_values($value);
            }

            // We need to transform all instances of the DateTime class into an actual
            // date string. Each query grammar maintains its own date string format
            // so we'll just ask the grammar for the format to get from the date.

            if ($value instanceof DateTime)
            {
                $binding = $value->format($grammar->getDateFormat());
            }

            $property = is_array($binding) ? key($binding) : $key;

            // We will set the binding key and value, then
            // we replace the binding property of the id (if found)
            // with a _nodeId instead since the client
            // will not accept replacing "id(n)" with a value
            // which have been previously processed by the grammar
            // to be _nodeId instead.
            if ( ! is_array($binding))
            {
                $binding = [$binding];
            }

            foreach ($binding as $property => $real)
            {
                // We should not pass any numeric key-value items since the Neo4j client expects
                // a JSON map parameters.
                if (is_numeric($property))
                {
                    $property = (! is_numeric($key)) ? $key : 'id';
                }

                if ($property == 'id') $property = $grammar->getIdReplacement($property);

                $prepared[$property] = $real;
            }
        }

        return $prepared;
    }
559525
private function buildErrorMessage(array $errorValues, array &$errors, $funcName, $propertyName)
    {
        $message = \str_replace(':attribute', "'".$propertyName."'", $errors[$funcName]);

        foreach ($errorValues as $key => $value) {
            $message = \str_replace(":{$key}", $value, $message);
        }

        return $message;
    }
1077845
private function _compile() {
		
		// remove spaces
		$this->_result = str_replace('{{ ', '{{', $this->_content);
		$this->_result = str_replace(' }}', '}}', $this->_result);
		
		// check if
		if ($this->ifs) {
			foreach ($this->ifs as $key => $val) {
				$this->_setBool($key, $val);
			}
			empty($this->ifs);
		}
		
		// check loop
		if ($this->loops) {
			foreach ($this->loops as $key => $val) {
				$this->_setArray($key, $val);
			}
			empty($this->loops);
		}
		
		// check static replaces
		if ($this->vars) {
			foreach ($this->vars as $key => $val) {
				$this->_setString($key, $val);
			}
			empty($this->vars);
		}
		
		// include global vars
		if (is_array($this->injects)) {
			foreach ($this->injects as $inject) {
				global $ {
					$inject
				};
			}
			extract($this->injects);
		}
		
		// remove if and loop traces
		$this->_result = preg_replace("/<if\..*?>(.*?)<\/if\..*?>/s", '', $this->_result);
		$this->_result = preg_replace("/<loop\..*?>(.*?)<\/loop\..*?>/s", '', $this->_result);
		
		// check dynamic variables
		$pattern = "\{\{(.*?)\}\}";
		preg_match_all("/" . $pattern . "/", $this->_result, $matches, PREG_SET_ORDER);
		foreach ($matches as $block) {
			$chunk = $block[0];
			$codes = '<?php ' . $this->config['echo'] . '(' . trim($block[1]) . ')' . '; ?>';
			$this->_result = str_replace($chunk, $codes, $this->_result);
		}
		
		// attempt to create cache file for this template in storage directory
		$cache_file = md5($this->_filename) . '.compiled';
		$cache = $this->config['dir_cache'] . '/' . $cache_file;
		$fd = @fopen($cache, 'w+');
		@fwrite($fd, $this->_result);
		@fclose($fd);
		
		// when failed, try to create in /tmp
		if (!file_exists($cache)) {
			$cache = '/tmp/' . $cache_file;
			$fd = @fopen($cache, 'w+');
			@fwrite($fd, $this->_result);
			@fclose($fd);
		}
		
		// if template cache file created then include it, else use eval() to compile
		if (file_exists($cache)) {
			ob_start();
			include $cache;
			$this->_compiled = ob_get_contents();
			ob_end_clean();
			@unlink($cache);
		} else {
			ob_start();
			eval('?>' . $this->_result . '<?php ');
			$this->_compiled = ob_get_contents();
			ob_end_clean();
		}
	}