生成类、接口、trait

@return void
337288
private function generateClasses()
    {
        foreach($this->ref->getClasses() as $class)
        {
            if($class->isInterface())
            {
                $this->generateInterface($class);
            }
            else if($class->isTrait())
            {
                $this->generateTrait($class);
            }
            else
            {
                $this->generateClass($class);
            }
        }
    }
262221
private function generateFunctions()
    {
        $result = '<?php' . PHP_EOL;
        foreach($this->ref->getFunctions() as $function)
        {
            $args = [];
            $comments = [];
            foreach($function->getParameters() as $param)
            {
                // 方法参数定义
                $args[] = $this->getMethodParamDefine($param);
                $comments[] = '@var ' . ($param->getType() ?? 'mixed') . ' $' . $param->name;
            }
            $return = $function->getReturnType();
            if(null !== $return)
            {
                $comments[] = '@return ' . $return;
            }
            $args = implode(', ', $args);
            if([] === $comments)
            {
                $comment = '';
            }
            else
            {
                $comment = implode(PHP_EOL . ' * ', $comments);
                $comment = <<<COMMENT

/**
 * {$comment}
 */
COMMENT;
            }
            $result .= <<<CODE
{$comment}
function {$function->name}({$args}){}

CODE;
        }
        file_put_contents($this->savePath . '/functions.php', $result);
    }
1054876
public function generateAction()
    {
        // Update Database
        $this->sqlCodeGenerator->updateDatabase();

        // Clear system cache to force new TCA caching
        $cacheManager = GeneralUtility::makeInstance(CacheManager::class);
        $cacheManager->flushCachesInGroup('system');
    }
985334
public static function generate()
    {
        self::dispatchEvent(self::EVENT_GET_MENU);

        $return = '';

        // sort menu by it's order
        uksort(self::$menu, 'strnatcmp');;

        /** @var Menu $item */
        foreach (self::$menu as $item) {
            if ($item->resources && !self::userHasResource($item->resources)) {
                continue;
            }

            if ($children = $item->getChildren()) {
                $subItems = '';

                // sort menu by it's order
                uksort($children, 'strnatcmp');;

                /** @var Menu $child */
                foreach ($children as $child) {
                    if ($child->resources && !self::userHasResource($child->resources)) {
                        continue;
                    }

                    $subItems .= '<li><a href="' . $child->getLink() . '">' . $child->getLabel() . '</a></li>';
                }

                $return .= '<li class="treeview">
                  <a href="#">
                    <i class="fa ' . $item->getIcon() . '"></i>
                    <span>' . $item->getLabel() . '</span>
                    <i class="fa fa-angle-left pull-right"></i>
                  </a>
                  <ul class="treeview-menu">
                    ' . $subItems . '
                  </ul>
                </li>';
            } else {
                $return .= '<li>
                        <a href="' . $item->getLink() . '">
                            <i class="fa ' . $item->getIcon() . ' fa-fw"></i> <span>' . $item->getLabel() . '</span>
                        </a>
                    </li>';
            }
        }

        return $return;
    }
926116
protected function registerTraits(): void
	{
		if(!isset(static::$traitHooks[static::class]))
		{
			static::$traitHooks[static::class] = [];
			static::$traitCasts[static::class] = [];

			foreach(ClassInspector::getTraits(static::class) as $trait)
			{
				if(method_exists($this, $getter = 'get' . $this->getClassShortName($trait) . 'Hooks'))
				{
					static::$traitHooks[static::class] = array_merge_recursive(static::$traitHooks[static::class], $this->$getter());
				}

				if(method_exists($this, $getter = 'get' . $this->getClassShortName($trait) . 'Casts'))
				{
					static::$traitCasts[static::class] += $this->$getter();
				}
			}
		}

		$this->cast += static::$traitCasts[static::class];
	}
357693
public function generateRemotingApi() {
        $list = array();
        foreach($this->remotingBundles as $bundle) {
            $bundleRef = new \ReflectionClass($bundle);
            $controllerDir = new Finder();
            $controllerDir->files()->in(dirname($bundleRef->getFileName()).'/Controller/')->name('/.*Controller\.php$/');
            foreach($controllerDir as $controllerFile) {
                $controller = $bundleRef->getNamespaceName() . "\\Controller\\" . substr($controllerFile->getFilename(), 0, -4);
                $controllerRef = new \ReflectionClass($controller);
                foreach ($controllerRef->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
                    /** @var $methodDirectAnnotation Direct */
                    $methodDirectAnnotation = $this->annoReader->getMethodAnnotation($method, 'Tpg\ExtjsBundle\Annotation\Direct');
                    if ($methodDirectAnnotation !== null) {
                        $nameSpace = str_replace("\\", ".", $bundleRef->getNamespaceName());
                        $className = str_replace("Controller", "", $controllerRef->getShortName());
                        $methodName = str_replace("Action", "", $method->getName());
                        $list[$nameSpace][$className][] = array(
                            'name'=>$methodName,
                            'len' => count($method->getParameters())
                        );
                    }
                }
            }
        }
        return $list;
    }
602099
public function generate() {
		$codeCompletionGenerator = $this->getGenerator();

		if ($this->param('dry-run')) {
			return static::CODE_SUCCESS;
		}

		$types = $codeCompletionGenerator->generate();

		$this->out('CodeCompletion files generated: ' . implode(', ', $types));

		return static::CODE_SUCCESS;
	}
1248913
public function index()
    {
        //  Validates the request token and generates a new one for the next request
        $this->validateToken();

        // --------------------------------------------------------------------------

        $oInput     = Factory::service('Input');
        $oAuthModel = Factory::model('Auth', 'nails/module-auth');

        if ($oInput->post('answer')) {

            /**
             * Validate the answer, if correct then log user in and forward, if
             * not then generate a new token and show errors
             */

            $this->data['question'] = $oAuthModel->mfaQuestionGet($this->mfaUser->id);
            $bIsValid               = $oAuthModel->mfaQuestionValidate(
                $this->data['question']->id,
                $this->mfaUser->id,
                $oInput->post('answer')
            );

            if ($bIsValid) {
                $this->loginUser();
            } else {
                $this->data['error'] = lang('auth_twofactor_answer_incorrect');
                $this->askQuestion();
            }

        } else {

            //  Determine whether the user has any security questions set
            $this->data['question'] = $oAuthModel->mfaQuestionGet($this->mfaUser->id);

            if ($this->data['question']) {

                //  Ask away cap'n!
                $this->askQuestion();

            } else {

                //  Fetch the security questions
                $this->data['questions'] = $this->authMfaConfig['questions'];

                /**
                 * Determine how many questions a user must have, if the number of questions
                 * is smaller than the number of questions available, use the smaller.
                 */
                if (count($this->data['questions']) < $this->authMfaConfig['numQuestions']) {
                    $this->data['num_questions'] = count($this->data['questions']);
                } else {
                    $this->data['num_questions'] = $this->authMfaConfig['numQuestions'];
                }

                //  The number of user generated questions a user must have
                $this->data['num_custom_questions'] = $this->authMfaConfig['numUserQuestions'];

                if ($this->data['num_questions'] + $this->data['num_custom_questions'] <= 0) {
                    throw new NailsException('Two-factor auth is enabled, but no questions available');
                }

                if ($oInput->post()) {

                    $oFormValidation = Factory::service('FormValidation');

                    for ($i = 0; $i < $this->data['num_questions']; $i++) {

                        $oFormValidation->set_rules(
                            'question[' . $i . '][question]',
                            '',
                            'required|is_natural_no_zero'
                        );

                        $oFormValidation->set_rules(
                            'question[' . $i . '][answer]',
                            '',
                            'trim|required'
                        );
                    }

                    for ($i = 0; $i < $this->data['num_custom_questions']; $i++) {

                        $oFormValidation->set_rules(
                            'custom_question[' . $i . '][question]',
                            '',
                            'trim|required'
                        );

                        $oFormValidation->set_rules(
                            'custom_question[' . $i . '][answer]',
                            '',
                            'trim|required'
                        );
                    }

                    $oFormValidation->set_message('required', lang('fv_required'));
                    $oFormValidation->set_message('is_natural_no_zero', lang('fv_required'));

                    if ($oFormValidation->run()) {

                        //  Make sure that we have different questions
                        $aQuestionIndex = [];
                        $aQuestion      = (array) $oInput->post('question', true);
                        $bError         = false;

                        foreach ($aQuestion as $q) {
                            if (array_search($q['question'], $aQuestionIndex) === false) {
                                $aQuestionIndex[] = $q['question'];
                            } else {
                                $bError = true;
                                break;
                            }
                        }

                        $aQuestionIndex = [];
                        $aQuestion      = (array) $oInput->post('custom_question', true);

                        foreach ($aQuestion as $q) {
                            if (array_search($q['question'], $aQuestionIndex) === false) {
                                $aQuestionIndex[] = $q['question'];
                            } else {
                                $bError = true;
                                break;
                            }
                        }

                        if (!$bError) {

                            //  Good arrows. Save questions
                            $aData = [];

                            if ($oInput->post('question', true)) {

                                foreach ($oInput->post('question', true) as $q) {

                                    $oTemp = new stdClass();

                                    if (isset($this->data['questions'][$q['question'] - 1])) {
                                        $oTemp->question = $this->data['questions'][$q['question'] - 1];
                                    } else {
                                        $oTemp->question = null;
                                    }
                                    $oTemp->answer = $q['answer'];

                                    $aData[] = $oTemp;
                                }
                            }

                            if ($oInput->post('custom_question', true)) {
                                foreach ((array) $oInput->post('custom_question', true) as $aQuestion) {
                                    $aData[] = (object) [
                                        'question' => trim($aQuestion['question']),
                                        'answer'   => $aQuestion['answer'],
                                    ];
                                }
                            }

                            if ($oAuthModel->mfaQuestionSet($this->mfaUser->id, $aData)) {

                                $sStatus  = 'success';
                                $sMessage = '<strong>Multi Factor Authentication Enabled!</strong><br />You ';
                                $sMessage .= 'successfully set your security questions. You will be asked to answer ';
                                $sMessage .= 'one of them every time you log in.';

                                $oSession = Factory::service('Session', 'nails/module-auth');
                                $oSession->setFlashData($sStatus, $sMessage);

                                $this->loginUser();

                            } else {

                                $oUserModel          = Factory::model('User', 'nails/module-auth');
                                $this->data['error'] = lang('auth_twofactor_question_set_fail');
                                $this->data['error'] .= ' ' . $oUserModel->lastError();
                            }

                        } else {
                            $this->data['error'] = lang('auth_twofactor_question_unique');
                        }

                    } else {
                        $this->data['error'] = lang('fv_there_were_errors');
                    }
                }

                //  No questions, request they set them
                $this->data['page']->title = lang('auth_twofactor_question_set_title');
                $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/mfa/question/set.php');
                Factory::service('View')
                    ->load([
                        'structure/header/blank',
                        'auth/mfa/question/set',
                        'structure/footer/blank',
                    ]);
            }
        }
    }
326410
public function generateVariants()
    {
        /**
         * @var array|null $aVariantParameters
         */
        $aVariantParameters = $this->getInputFilterUtil()->getFilteredInput('variantParameters');
        if (null === $aVariantParameters) {
            return '';
        }

        foreach ($aVariantParameters as $aVariant) {
            $oTableEditorManager = new TCMSTableEditorManager();
            $oTableEditorManager->sRestrictionField = 'variant_parent_id';
            $oTableEditorManager->sRestriction = $this->oTableRow->id;
            $oTableEditorManager->Init($this->oDefinition->fieldCmsTblConfId, $this->oTableRow->id);
            $oTableEditorManager->AllowEditByAll(true);
            $oTableEditorManager->Insert();
            $oTableEditorManager->oTableEditor->SaveFields($this->mapVariantArticleData($aVariant));

            foreach ($aVariant['variantIDs'] as $sVariantID) {
                $oTableEditorManager->AddMLTConnection($this->name, $sVariantID);
            }

            $nameList = $this->getProductVariantNameGenerator()->generateNamesForAllLanguages($oTableEditorManager->oTableEditor->oTable);
            $originalLanguageId = $oTableEditorManager->oTableEditor->oTableConf->GetLanguage();
            foreach ($nameList as $languageId => $name) {
                $oTableEditorManager->oTableEditor->oTableConf->SetLanguage($languageId);
                $oTableEditorManager->SaveField('name_variant_info', $name);
            }
            $oTableEditorManager->oTableEditor->oTableConf->SetLanguage($originalLanguageId);
        }

        return TGlobal::Translate('chameleon_system_shop.field_shop_variant_details.msg_created_variants', array('%generatedVariantsCount%' => count($aVariantParameters)));
    }
215213
public function actionGenerate()
	{
		$passwordList = \App::$domain->tool->password->generate();
		$text = implode(SPC, $passwordList);
		Output::line();
		Output::pipe('Generated passwords');
		Output::autoWrap($text);
		Output::pipe();
		Output::line();
	}
712695
public function generate()
    {
        $create_at = date("YmdHis");
        $filename = sprintf("Version%s%s", $create_at, ucfirst(Str::camel('sessions')));

        $generator = new Generator(
            $this->setting->getMigrationDirectory(),
            $filename
        );

        $generator->write('model/session', [
            'className' => $filename
        ]);

        echo Color::green('Session migration created.');
    }
447568
public function generate()
    {
        $code = array();

        $body = $this->getExtraBody();
        $bodyHasOpenTag = preg_match('#(?:\s*)<\?php#', $body);
        $code[] = '<?php';
        $code[] = null;

        // Documentation.
        $doc = $this->generateDocumentation();
        if ($doc !== null) {
            $code[] = $doc;
            $code[] = null;
        }

        foreach ($this->objects as $object) {
            foreach ($object->getUses() as $use => $alias) {
                $this->addUse($use, $alias);
            }
        }

        // If there are objects in different namespaces or some objects are in a different namespace compared to the file namespace.
        if ($this->areMultipleNamespacesInFile() === true) {
            $code = array_merge($code, $this->renderObjects(true));

            $code[] = $this->getIndentation() . 'namespace ' . $this->namespace;
            $code[] = '{';
            $code[] = null;

            // Temporarily add one more level of indentation.
            $this->addIndentationLevel(1);

            $code = array_merge($code, $this->renderRequiredFilesLines());

            $code = array_merge($code, $this->renderUsesLines());

            if ($bodyHasOpenTag > 0) {
                $code[] = '?>';
            }

            if ($this->extraBody !== null) {
                $code[] = $this->extraBody;
            }

            // Set back the indentation.
            $this->addIndentationLevel(-1);

            $code[] = $this->getIndentation() . '}';
        } else {
            if ($this->namespace !== null) {
                $code[] = $this->getIndentation() . 'namespace ' . $this->namespace . ';';
                $code[] = null;
            }

            $code = array_merge($code, $this->renderRequiredFilesLines());

            $code = array_merge($code, $this->renderUsesLines());

            $code = array_merge($code, $this->renderObjects(false));

            if ($bodyHasOpenTag > 0) {
                $code[] = '?>';
            }

            if ($this->extraBody !== null) {
                $code[] = $this->extraBody;
            }
        }

        return implode($this->getLineFeed(), $code);
    }
945831
public function generate(): string
    {
        $classCode = $this->generator->generate();

        return $classCode
            // Inject advices on call
            . '\\' . __CLASS__ . '::injectJoinPoints(' . $this->generator->getName() . '::class);';
    }
459449
protected function createTraitFile($trait)
    {
        $dir_option = rtrim(str_replace('/', '\\', $this->getDirOption()), '/\\');
        $dir_option = $dir_option ? '\\' . $dir_option : '';
        $trait = $this->configureName('trait', $trait);

        $stub = str_replace(
            ['{{Namespace}}', '{{TraitName}}'],
            [$this->getTraitDirectoryFromConfig() . $dir_option, $trait],
            $this->files->get(__DIR__ . '/../stubs/trait.stub')
        );

        $this->files->put(base_path() . '/' . $this->getTraitDirectory() . $this->getDirOption() . $trait . '.php', $stub);
    }
1192426
public function create()
    {
        $this->getIdHandler()->generateId();

        $this->values = array();

        $this->firstTrace = time();
        $this->updateLastTrace();

        $this->requestsCount = 1;
        $this->regenerationTrace = time();

        $this->fingerprint = $this->generateFingerprint();

        $this->opened = true;

        return $this->opened;
    }
530977
protected function generateMethodsLines()
    {
        $code = array();
        foreach ($this->methods as $method) {
            $method->setIndentationString($this->getIndentationString());
            $method->setIndentationLevel($this->getIndentationLevel() + 1);
            $code[] = $method->generate();
            $code[] = null;
        }

        return $code;
    }
902036
public function actionGenerate()
    {
        $this->stdout("Polary Devkit Tool (based on Yii)\n\n");
        try {
            $component = $this->getComponent();
            $configList = $this->getConfig($component);
            $config = new Config([
                'files' => $configList,
            ]);
            $builder = new Builder([
                'components' => $config->getComponents(),
                'template'   => require __DIR__ . '/templates/helper.php',
            ]);
            if ($component->result === null) {
                $component->result = ($this->getDetector()->detect() === 'basic') ?
                    '@app/_ide_components.php' :
                    '@console/../_ide_components.php';
            }

            $result = Yii::getAlias($component->result);
            $result = FileHelper::normalizePath($result);

            $this->stdout("Generate new IDE auto-completion code '{$result}'\n");
            $time = microtime(true);
            $builder->build($result);
            $this->stdout('New auto-completion code created successfully. (time: ' . sprintf('%.3f', microtime
                    (true) - $time) . "s)\n", Console::FG_GREEN);
        } catch (Exception $exception) {
            $this->stdout('Generate failed ' . $exception->getMessage() .  "\n", Console::FG_RED);
        }
    }