Generates the SQL from a YASQL file

Arguments:

string $1 Path to YASQL file
int    $2 How many spaces per indentation level

@param Event $event Composer run-script event
187678
public static function generate(Event $event)
    {
        $args = $event->getArguments();
        if (empty($args)) {
            echo "Usage:\n\n"
                . "    composer yasql-generate -- YASQL_FILE [INDENTATION]\n\n"
                . "By default, INDENTATION is 2\n";
            die(1);
        }

        echo Controller::generate(
            file_get_contents($args[0]),
            null,
            $args[1] ?? 2
        );
    }
478951
public function formatSql($sql, $tabOffset = 3)
    {
        $tab = Formatter::$tab;
        $indent = '';

        for ($i = 0; $i < $tabOffset; ++$i) {
            $indent .= $tab;
        }

        $sql = explode("\n", Formatter::format($sql, false));
        $indentedLines = array();

        foreach ($sql as $line) {
            $indentedLines[] = $indent.str_replace('"', '\"', $line);
        }

        return implode("\n", $indentedLines);
    }
325619
public static function execute(Event $event) {
    $composer = $event->getComposer();
    $handler = new static(
      $composer->getPackage(),
      $composer->getLocker()
    );
    $encoder = new IniEncoder();
    $make = $handler->make();
    $core = $handler->makeCore($make);
    file_put_contents('drupal-org-core.make', $encoder->encode($core));
    file_put_contents('drupal-org.make', $encoder->encode($make));
  }
1223146
function indent(level) {
    var val = options.indent
    _indent = ''

    if (_lastch === null)
      _lastch = _to                 // as-is, this is the first file
    else if (_lastch !== _to) {
      _lastch = _to
      // istanbul ignore else
      if (output)
        output.emit('data', _to)    // force eol after insert file
    }

    if (level > 0 && val && !/^0+\D?/.test(val)) {
      // format is 2, 2t, 2s, etc. default is spaces
      var match = /^(\d+)\s*(t?)/.exec(val),
          count = level * (match[1] | 0)
      _indent = Array(count + 1).join(match[2] ? '\t' : ' ')
    }
  }
675955
function generateTableInsertSQLList( $tableName, $tableDef, $dataEntries, $params, $withClosure = true )
    {
        $sqlList = eZDBSchemaInterface::generateTableInsertSQLList( $tableName, $tableDef, $dataEntries, $params, $withClosure );

        foreach ( $tableDef['fields'] as $fieldName => $fieldDef )
        {
            if ( $fieldDef['type'] == 'auto_increment' )
            {
                $sql = "SELECT setval('" . $tableName . "_{$fieldName}_seq',max(" . $fieldName . ")+1) FROM " . $tableName;
                if ( $withClosure )
                    $sql .= ";";
                $sqlList[] = $sql;
            }
        }
        return $sqlList;
    }
765065
public function compileBindsQuestionMark(string $sql, $binds = null)
    {
        if (empty($binds) || strpos($sql, '?') === false) {
            return $sql;
        } elseif (! is_array($binds)) {
            $binds = [$binds];
            $bind_count = 1;
        } else {
            // Make sure we're using numeric keys
            $binds = array_values($binds);
            $bind_count = count($binds);
        }
        // Make sure not to replace a chunk inside a string that happens to match the bind marker
        if ($countMatches = preg_match_all("/'[^']*'/i", $sql, $matches)) {
            $countMatches = preg_match_all(
                '/\?/i', # regex
                str_replace(
                    $matches[0],
                    str_replace('?', str_repeat(' ', 1), $matches[0]),
                    $sql,
                    $countMatches
                ),
                $matches, # matches
                PREG_OFFSET_CAPTURE
            );
            // Bind values' count must match the count of markers in the query
            if ($bind_count !== $countMatches) {
                return false;
            }
        } elseif (($countMatches = preg_match_all('/\?/i', $sql, $matches, PREG_OFFSET_CAPTURE)) !== $bind_count) {
            return $sql;
        }

        do {
            $countMatches--;
            $escapedValue = is_int($binds[$countMatches])
                ? $binds[$countMatches]
                : $this->quote($binds[$countMatches]);
            if (is_array($escapedValue)) {
                $escapedValue = '('.implode(',', $escapedValue).')';
            }
            $sql = substr_replace($sql, $escapedValue, $matches[0][$countMatches][1], 1);
        } while ($countMatches !== 0);

        return $sql;
    }
1015873
public function getString($indent = 2, $wordWrap = false)
    {
        $res = $this->driverInstance->getString($indent, $wordWrap);
        if (!$this->isString($res) && !$this->isStringObject($res)) {
            throw new YamlException('YamlInterface method _getString() must return a string or StringObject.');
        }

        return StdObjectWrapper::toString($res);
    }
908445
public static function populateEnvironment(Event $event)
    {
        $url = getenv('CLEARDB_DATABASE_URL');

        if ($url) {
            $url = parse_url($url);
            putenv("SYMFONY_DATABASE_HOST={$url['host']}");
            putenv("SYMFONY_DATABASE_USER={$url['user']}");
            putenv("SYMFONY_DATABASE_PASSWORD={$url['pass']}");

            $db = substr($url['path'], 1);
            putenv("SYMFONY_DATABASE_NAME={$db}");
            putenv("SYMFONY_PROD_LOG_PATH=php://stderr");

            $io = $event->getIO();
            $io->write('CLEARDB_DATABASE_URL=' . getenv('CLEARDB_DATABASE_URL'));
            $io->write('SYMFONY_PROD_LOG_PATH=' . getenv('SYMFONY_PROD_LOG_PATH'));
        }
    }
120788
private function format_connection_string() {
		if (!in_array($this->dbtype, ['sqlite3', 'mysql', 'pgsql'])) {
			$this->verified_params = null;
			self::$logger->error(sprintf(
				"SQL: database not supported: '%s'.",
				$this->dbtype));
			throw new SQLError(SQLError::DBTYPE_ERROR,
				$this->dbtype . " not supported.");
		}

		if ($this->dbtype == 'sqlite3')
			return $this->connection_string = 'sqlite:' . $this->dbname;

		if (!$this->dbuser) {
			$this->verified_params = null;
			self::$logger->error(
				"SQL: param not supplied: 'dbuser'.");
			throw new SQLError(
				SQLError::CONNECTION_ARGS_ERROR,
				"'dbuser' not supplied.");
		}

		$cstr = sprintf("%s:dbname=%s", $this->dbtype, $this->dbname);
		if ($this->dbhost) {
			$cstr .= sprintf(';host=%s', $this->dbhost);
			if ($this->dbport)
				$cstr .= sprintf(';port=%s', $this->dbport);
		}

		if ($this->dbtype == 'mysql')
			# mysql uses dbuser and dbpass on PDO constructor
			return $this->connection_string = $cstr;

		$cstr .= sprintf(";user=%s", $this->dbuser);
		if ($this->dbpass)
			$cstr .= sprintf(";password=%s", $this->dbpass);
		return $this->connection_string = $cstr;
	}
1053584
function _DBParameter($sql)
	{
		$savelog = $this->conn->LogSQL(false);
		if (is_array($sql)) {
		global $ADODB_FETCH_MODE;

			$sql1 = $sql[0];
			$key = $sql[1];
			if (sizeof($sql)>2) $pos = $sql[2];
			else $pos = 1;
			if (sizeof($sql)>3) $coef = $sql[3];
			else $coef = false;
			$ret = false;
			$save = $ADODB_FETCH_MODE;
			$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
			if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);

			$rs = $this->conn->Execute($sql1);

			if (isset($savem)) $this->conn->SetFetchMode($savem);
			$ADODB_FETCH_MODE = $save;
			if ($rs) {
				while (!$rs->EOF) {
					$keyf = reset($rs->fields);
					if (trim($keyf) == $key) {
						$ret = $rs->fields[$pos];
						if ($coef) $ret *= $coef;
						break;
					}
					$rs->MoveNext();
				}
				$rs->Close();
			}
			$this->conn->LogSQL($savelog);
			return $ret;
		} else {
			if (strncmp($sql,'=',1) == 0) {
				$fn = substr($sql,1);
				return $this->$fn();
			}
			$sql = str_replace('$DATABASE',$this->conn->database,$sql);
			$ret = $this->conn->GetOne($sql);
			$this->conn->LogSQL($savelog);

			return $ret;
		}
	}
335893
private function buildFields(array $fields, $indent, array &$result)
    {
        $stringified_field_names = [];
        $fields_with_default_value = [];

        foreach ($fields as $field) {
            if ($field instanceof ScalarField && $field->getShouldBeAddedToModel()) {
                $stringified_field_names[] = var_export($field->getName(), true);

                if ($field->getName() != 'id' && $field->getDefaultValue() !== null) {
                    $fields_with_default_value[$field->getName()] = $field->getDefaultValue();
                }
            }
        }

        $result[] = '';
        $result[] = $indent . '/**';
        $result[] = $indent . ' * Table fields that are managed by this entity.';
        $result[] = $indent . ' *';
        $result[] = $indent . ' * @var array';
        $result[] = $indent . ' */';
        $result[] = $indent . 'protected $fields = [' . implode(', ', $stringified_field_names) . '];';

        if (count($fields_with_default_value)) {
            $result[] = '';
            $result[] = $indent . '/**';
            $result[] = $indent . ' * List of default field values.';
            $result[] = $indent . ' *';
            $result[] = $indent . ' * @var array';
            $result[] = $indent . ' */';
            $result[] = $indent . 'protected $default_field_values = [';

            foreach ($fields_with_default_value as $field_name => $default_value) {
                $result[] = $indent . '   ' . var_export($field_name, true) . ' => ' . var_export($default_value, true) . ',';
            }

            $result[] = $indent . '];';
        }
    }
670109
public static function composerGenerate($event = null)
    {
        if ($event) {
            $event->getIO()->write('Generating BespokeSupport\Mime\FileMimes class');
        }

        $file = __DIR__ . '/../resources/mimes.csv';

        self::fetch($file);

        self::generate($file);
    }
639308
public function onCommandAfterPrepare(Event $event) {

        $command = $event['command'];
        $bucket = $command['Bucket'];
        $request = $command->getRequest();
        if ($command->getName() == 'ListBuckets')
        {
            if ($this->ipport != null) {
                $request->setHost($this->ipport);
                $request->setHeader('Host', 'service.cos.myqcloud.com');
            } else if ($this->endpoint != null) {
                $request->setHost($this->endpoint);
                $request->setHeader('Host', 'service.cos.myqcloud.com');
            }
            else {

                $request->setHost('service.cos.myqcloud.com');
            }
            return ;
        }
        if ($key = $command['Key']) {
            // Modify the command Key to account for the {/Key*} explosion into an array
            if (is_array($key)) {
                $command['Key'] = $key = implode('/', $key);
            }
        }
        $request->setHeader('Date', gmdate('D, d M Y H:i:s T'));
        $request->setPath(preg_replace("#^/{$bucket}#", '', $request->getPath()));

        if ($this->appId != null && endWith($bucket,'-'.$this->appId) == False)
        {
            $bucket = $bucket.'-'.$this->appId;
        }
//        $request->setPath(urldecode($request->getPath()));
        $request->getParams()->set('bucket', $bucket)->set('key', $key);

        $realHost = $bucket. '.' . $request->getHost();
        if($this->ipport != null) {
            $request->setHost($this->ipport);
            $request->setHeader('Host', $realHost);
        } else {
            if($this->endpoint != null) {
                $tmp = $bucket. '.' . $this->endpoint;
                $request->setHost($tmp);
            } else {
                $request->setHost($realHost);
            }
        }
        if (!$bucket) {
            $request->getParams()->set('cos.resource', '/');
        } else {
            // Bucket style needs a trailing slash
            $request->getParams()->set(
                'cos.resource',
                '/' . rawurlencode($bucket) . ($key ? ('/' . Client::encodeKey($key)) : '/')
            );
        }
    }
744298
protected function createSelectString($columns)
    {
        $dbDriver = $this->getConnection()->getDriverName();

        switch ($dbDriver) {
            case 'pgsql':
            case 'sqlite':
                $columnString = implode(" || ' ' || " . $this->getConnection()->getTablePrefix() . $this->getUsersTable() . ".", $columns);
                $selectString = "(" . $this->getConnection()->getTablePrefix() . $this->getUsersTable() . "." . $columnString . ") as name";
                break;
            case 'sqlsrv':
                $columnString = implode(" + ' ' + " . $this->getConnection()->getTablePrefix() . $this->getUsersTable() . ".", $columns);
                $selectString = "(" . $this->getConnection()->getTablePrefix() . $this->getUsersTable() . "." . $columnString . ") as name";
                break;
            default:
                $columnString = implode(", ' ', " . $this->getConnection()->getTablePrefix() . $this->getUsersTable() . ".", $columns);
                $selectString = "concat(" . $this->getConnection()->getTablePrefix() . $this->getUsersTable() . "." . $columnString . ") as name";
        }

        return $selectString;
    }
110040
public static function meatOnBones(Event $event)
    {
        $basePath = realpath(".");
        $handler = new ComposerHydrationHandler($event, $basePath);

        $handler->hydrate();
    }
840027
private function _yamlize($key,$value,$indent, $previous_key = -1, $first_key = 0, $source_array = null)
  {
    if (is_array($value)) {
      if (empty ($value))
        return $this->_dumpNode($key, array(), $indent, $previous_key, $first_key, $source_array);
      // It has children.  What to do?
      // Make it the right kind of item
      $string = $this->_dumpNode($key, self::REMPTY, $indent, $previous_key, $first_key, $source_array);
      // Add the indent
      $indent += $this->_dumpIndent;
      // Yamlize the array
      $string .= $this->_yamlizeArray($value,$indent);
    } elseif (!is_array($value)) {
      // It doesn't have children.  Yip.
      $string = $this->_dumpNode($key, $value, $indent, $previous_key, $first_key, $source_array);
    }

    return $string;
  }
373753
public static function createConfigJson( Event $event ) {
		if ( ! defined( 'WPEMERGE_CLI_DIR' ) ) {
			define( 'WPEMERGE_CLI_DIR', dirname( __DIR__ ) );
		}

		$input = new ArrayInput( [ 'config:create' ] );
		$output = new BufferedOutput();

		try {
			$application = static::create();
			$command = $application->find('config:create');
			$command->run( $input, $output );
			$event->getIO()->write( $output->fetch() );
		} catch ( RuntimeException $e ) {
			$event->getIO()->write( '<error>' . $e->getMessage() . '</error>' );
		}
	}