sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function put($file, $content, $flag = null, $recursive = false) { if ($recursive) { $this->createParentFolder($file); } return file_put_contents($this->getPath($file), $content, $flag); }
Put content in file. @param $file @param $content @param $flag @param bool $recursive @return int
entailment
public function createParentFolder($file) { if (! file_exists($folder = dirname($file))) { return mkdir(dirname($file), 0775, true); } }
Create parent folder recursively (if not exists). @param $file @return bool
entailment
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); $loader->load('services-repositories.yml'); $loader->load('services-admin.yml'); $loader->load('services-cache.yml'); $twigExtensionDefinition = $container->getDefinition('harentius_blog.twig.blog_extension'); $cacheService = ($config['sidebar']['cache_lifetime'] === null) ? 'harentius_blog.array_cache' : 'harentius_blog.sidebar.cache' ; $cacheServiceDefinition = $container->getDefinition($cacheService); $twigExtensionDefinition->replaceArgument(1, $cacheServiceDefinition); $articleAdminDefinition = $container->getDefinition('harentius_blog.admin.article'); $articleAdminDefinition->addMethodCall('setControllerCache', [$cacheServiceDefinition]); $container->setParameter('harentius_blog.sidebar.tags_limit', $config['sidebar']['tags_limit']); $container->setParameter('harentius_blog.sidebar.tag_sizes', $config['sidebar']['tag_sizes']); $container->setParameter('harentius_blog.homepage.page_slug', $config['homepage']['page_slug']); $container->setParameter('harentius_blog.homepage.feed.category', $config['homepage']['feed']['category']); $container->setParameter('harentius_blog.homepage.feed.number', $config['homepage']['feed']['number']); $container->setParameter('harentius_blog.list.posts_per_page', $config['list']['posts_per_page']); $container->setParameter('harentius_blog.cache.apc_global_prefix', $config['cache']['apc_global_prefix']); $container->setParameter('harentius_blog.cache.statistics_cache_lifetime', $config['cache']['statistics_cache_lifetime']); $container->setParameter('harentius_blog.sidebar.cache_lifetime', $config['sidebar']['cache_lifetime']); $container->setParameter('harentius_blog.homepage.page_slug', $config['homepage']['page_slug']); $container->setParameter('harentius_blog.articles.image_previews_base_uri', $config['articles']['image_previews_base_uri']); $container->setParameter('harentius_blog.locales', $config['locales']); $container->setParameter('harentius_blog.articles.sharethis.property', $config['articles']['sharethis']['property']); $container->setParameter('harentius_blog.articles.sharethis.product', $config['articles']['sharethis']['product']); }
{@inheritdoc}
entailment
public function getInstancesOf(string $type, bool $reverseOrder = false): array { $plugins = array_filter( $this->getInstances(), function ($plugin) use ($type) { return is_a($plugin, $type); } ); if ($reverseOrder) { $plugins = array_reverse($plugins, true); } return array_diff_key($plugins, array_flip($this->disabled)); }
Returns the active plugin instances of a given type (see class constants). @return array<string,BundlePluginInterface>
entailment
public function parse($resource, $type = null): array { foreach ($this->parsers as $parser) { if ($parser->supports($resource, $type)) { return $parser->parse($resource, $type); } } throw new \InvalidArgumentException(sprintf('Cannot parse resources "%s" (type: %s)', $resource, $type)); }
{@inheritdoc}
entailment
public function supports($resource, $type = null): bool { foreach ($this->parsers as $parser) { if ($parser->supports($resource, $type)) { return true; } } return false; }
{@inheritdoc}
entailment
protected function addRuleLine($directories, $rule) { foreach ((array) $directories as $directory) { $this->addLine($rule.': '.$directory); } }
Add a rule to the robots.txt. @param string|array $directories @param string $rule
entailment
public function getBundleConfigs(bool $development, string $cacheFile = null): array { if (null !== $cacheFile) { return $this->loadFromCache($development, $cacheFile); } return $this->loadFromPlugins($development, $cacheFile); }
Returns an ordered bundles map. @return ConfigInterface[]
entailment
private function loadFromCache(bool $development, string $cacheFile = null): array { $bundleConfigs = is_file($cacheFile) ? include $cacheFile : null; if (!\is_array($bundleConfigs) || 0 === \count($bundleConfigs)) { $bundleConfigs = $this->loadFromPlugins($development, $cacheFile); } return $bundleConfigs; }
Loads the bundles map from cache. @return ConfigInterface[]
entailment
private function loadFromPlugins(bool $development, string $cacheFile = null): array { $resolver = $this->resolverFactory->create(); /** @var BundlePluginInterface[] $plugins */ $plugins = $this->pluginLoader->getInstancesOf(PluginLoader::BUNDLE_PLUGINS); foreach ($plugins as $plugin) { foreach ($plugin->getBundles($this->parser) as $config) { $resolver->add($config); } } $bundleConfigs = $resolver->getBundleConfigs($development); if (null !== $cacheFile) { $this->filesystem->dumpFile($cacheFile, sprintf('<?php return %s;', var_export($bundleConfigs, true))); } return $bundleConfigs; }
Generates the bundles map. @return ConfigInterface[]
entailment
public function parse($resource, $type = null): array { $configs = []; $config = new ModuleConfig($resource); $configs[] = $config; $this->loaded[$resource] = true; $path = $this->modulesDir.'/'.$resource.'/config/autoload.ini'; if (file_exists($path)) { $requires = $this->parseIniFile($path); if (0 !== \count($requires)) { // Recursively load all modules that are required by other modules foreach ($requires as &$module) { if (0 === strncmp($module, '*', 1)) { $module = substr($module, 1); // Do not add optional modules that are not installed if (!is_dir($this->modulesDir.'/'.$module)) { continue; } } if (!isset($this->loaded[$module])) { $configs = array_merge($configs, $this->parse($module)); } } unset($module); $config->setLoadAfter($requires); } } return $configs; }
{@inheritdoc}
entailment
public function supports($resource, $type = null): bool { return 'ini' === $type || is_dir($this->modulesDir.'/'.$resource); }
{@inheritdoc}
entailment
private function parseIniFile(string $file): array { $ini = parse_ini_file($file, true); if (!\is_array($ini)) { throw new \RuntimeException("File $file cannot be decoded"); } if (!isset($ini['requires']) || !\is_array($ini['requires'])) { return []; } return $ini['requires']; }
Parses the file and returns the configuration array. @throws \RuntimeException If the file cannot be decoded
entailment
public function activate(Composer $composer, IOInterface $io): void { $packagesDir = $composer->getConfig()->get('data-dir').'/packages'; if (!is_dir($packagesDir) || !class_exists(\ZipArchive::class)) { return; } $repository = $this->addArtifactRepository($composer, $packagesDir); if (null === $repository) { return; } $this->registerProviders($repository, $composer); }
{@inheritdoc}
entailment
public function getRouteCollectionForRequest(Request $request) { foreach ($this->categorySlugProvider->getAll() as $categoryId => $fullSlug) { $this->routes->add("harentius_blog_category_{$categoryId}", new Route( "/category{$fullSlug}", ['_controller' => 'HarentiusBlogBundle:Blog:list', 'filtrationType' => 'category', 'criteria' => $categoryId] )); } return $this->routes; }
{@inheritdoc}
entailment
public function getRouteByName($name, $params = []) { if ($route = $this->routes->get($name)) { return $route; } return null; }
{@inheritdoc}
entailment
public function process(ContainerBuilder $container) { $defaultLocale = $container->getParameter('kernel.default_locale'); $locales = $container->getParameter('harentius_blog.locales'); $supportedLocalesWithoutDefault = $locales; if (($key = array_search($defaultLocale, $supportedLocalesWithoutDefault, true)) !== false) { unset($supportedLocalesWithoutDefault[$key]); } $container->setParameter( 'harentius_blog.supported_locales_without_default', implode('|', $supportedLocalesWithoutDefault) ); }
{@inheritdoc}
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('harentius_blog'); $rootNode->children() ->arrayNode('locales') ->prototype('scalar')->end() ->end() ->arrayNode('sidebar') ->children() ->scalarNode('cache_lifetime')->defaultValue(0)->end() ->integerNode('tags_limit')->defaultValue(10)->end() ->arrayNode('tag_sizes') ->prototype('integer')->end() ->end() ->end() ->end() ->arrayNode('homepage') ->children() ->scalarNode('page_slug')->defaultValue(null)->end() ->end() ->children() ->arrayNode('feed') ->children() ->scalarNode('category')->defaultValue(null)->end() ->scalarNode('number')->defaultValue(null)->end() ->end() ->end() ->end() ->end() ->arrayNode('list') ->children() ->integerNode('posts_per_page')->defaultValue(10)->end() ->end() ->end() ->arrayNode('cache') ->children() ->scalarNode('apc_global_prefix')->defaultValue('harentius_blog')->end() ->integerNode('statistics_cache_lifetime')->defaultValue(86400)->end() ->end() ->end() ->arrayNode('articles') ->children() ->scalarNode('image_previews_base_uri')->defaultValue('/assets/images/preview/')->end() ->arrayNode('sharethis') ->children() ->scalarNode('property')->defaultValue(null)->end() ->scalarNode('product')->defaultValue('inline-share-buttons')->end() ->end() ->end() ->end() ->end() ; return $treeBuilder; }
{@inheritdoc}
entailment
public function getBundleConfigs($development): array { $bundles = []; // Only add bundles which match the environment foreach ($this->configs as $config) { if (($development && $config->loadInDevelopment()) || (!$development && $config->loadInProduction())) { $bundles[$config->getName()] = $config; } else { unset($bundles[$config->getName()]); } } $loadingOrder = $this->buildLoadingOrder(); $replaces = $this->buildReplaceMap(); $normalizedOrder = $this->normalizeLoadingOrder($loadingOrder, $replaces); $resolvedOrder = $this->orderByDependencies($normalizedOrder); return $this->order($bundles, $resolvedOrder); }
{@inheritdoc}
entailment
public function populateSitemap(SitemapPopulateEvent $event) { $event->getGenerator()->addUrl( new UrlConcrete( $this->router->generate('harentius_blog_homepage', [], true), $this->homepage->getUpdatedAt(), UrlConcrete::CHANGEFREQ_WEEKLY, 1.0 ), 'pages' ); // Pages $pages = $this->pageRepository->findPublishedNotSlugOrdered($this->homepageSlug); foreach ($pages as $page) { $event->getGenerator()->addUrl( new UrlConcrete( $this->router->generate('harentius_blog_show', ['slug' => $page->getSlug()], true), $page->getUpdatedAt(), UrlConcrete::CHANGEFREQ_MONTHLY, 0.5 ), 'pages' ); } // Articles /** @var Article[] $articles */ $articles = $this->articleRepository->findBy(['published' => true], ['publishedAt' => 'DESC']); foreach ($articles as $article) { $event->getGenerator()->addUrl( new UrlConcrete( $this->router->generate('harentius_blog_show', ['slug' => $article->getSlug()], true), $article->getUpdatedAt(), UrlConcrete::CHANGEFREQ_MONTHLY, 0.9 ), 'articles' ); } // Categories $addCategoriesRoutes = function ($categories) use ($event, &$addCategoriesRoutes) { foreach ($categories as $category) { $event->getGenerator()->addUrl( new UrlConcrete( $this->router->generate("harentius_blog_category_{$category['id']}", [], true), null, UrlConcrete::CHANGEFREQ_MONTHLY, 0.8 ), 'categories' ); $addCategoriesRoutes($category['__children']); } }; $addCategoriesRoutes($this->categoryRepository->notEmptyChildrenHierarchy()); }
{@inheritdoc}
entailment
public function make() { $this->rawColumns = $this->getRawColumns($this->columns); $this->columnNames = $this->getColumnNames(); $this->addSelect(); $this->total = $this->count(); if (static::$versionTransformer === null) { static::$versionTransformer = new Version110Transformer(); } $this->addFilters(); $this->filtered = $this->count(); $this->addOrderBy(); $this->addLimits(); $this->rows = $this->builder->get(); $rows = []; foreach ($this->rows as $row) { $rows[] = $this->formatRow($row); } return [ static::$versionTransformer->transform('draw') => (isset($_POST[static::$versionTransformer->transform( 'draw' )]) ? (int)$_POST[static::$versionTransformer->transform('draw')] : 0), static::$versionTransformer->transform('recordsTotal') => $this->total, static::$versionTransformer->transform('recordsFiltered') => $this->filtered, static::$versionTransformer->transform('data') => $rows ]; }
Make the datatable response. @return array @throws Exception
entailment
protected function addFilters() { $search = static::$versionTransformer->getSearchValue(); if ($search != '') { $this->addAllFilter($search); } $this->addColumnFilters(); return $this; }
Add the filters based on the search value given. @return $this
entailment
protected function addAllFilter($search) { $this->builder = $this->builder->where( function ($query) use ($search) { foreach ($this->columns as $column) { $query->orWhere( new raw($this->getRawColumnQuery($column)), 'like', '%' . $search . '%' ); } } ); }
Searches in all the columns. @param $search
entailment
protected function addColumnFilters() { foreach ($this->columns as $i => $column) { if (static::$versionTransformer->isColumnSearched($i)) { $this->builder->where( new raw($this->getRawColumnQuery($column)), 'like', '%' . static::$versionTransformer->getColumnSearchValue($i) . '%' ); } } }
Add column specific filters.
entailment
protected function addOrderBy() { if (static::$versionTransformer->isOrdered()) { foreach (static::$versionTransformer->getOrderedColumns() as $index => $direction) { if (isset($this->columnNames[$index])) { $this->builder->orderBy( $this->columnNames[$index], $direction ); } } } }
Depending on the sorted column this will add orderBy to the builder.
entailment
protected function addLimits() { if (isset($_POST[static::$versionTransformer->transform( 'start' )]) && $_POST[static::$versionTransformer->transform('length')] != '-1' ) { $this->builder->skip((int)$_POST[static::$versionTransformer->transform('start')])->take( (int)$_POST[static::$versionTransformer->transform('length')] ); } }
Adds the pagination limits to the builder
entailment
public function resizeAction($imageName) { try { $imageOptimizer = $this->get('harentius_blog.image_optimizer'); $imagePath = $imageOptimizer->createPreviewIfNotExists($imageName); return new BinaryFileResponse($imagePath); } catch (\Exception $e) { throw new NotFoundHttpException(sprintf('File %s not found', $imageName)); } }
For optimization, try_files should be set in nginx Then BinaryFileResponse only once, when crete cache preview. @param string $imageName @return Response
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $em = $this->getContainer()->get('doctrine.orm.entity_manager'); /** @var AdminUser $adminUser */ $adminUser = $em->getRepository('HarentiusBlogBundle:AdminUser')->findOneBy(['username' => 'admin']); if ($adminUser) { throw new \RuntimeException('Admin User not found'); } $adminUser->setPlainPassword($input->getArgument('password')); $em->flush(); $output->writeln('Password successfully changed'); }
{@inheritdoc}
entailment
protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('title') ->add('slug', null, [ 'required' => false, ]) ->add('category') ->add('tags', 'sonata_type_model_autocomplete', [ 'attr' => [ 'class' => 'tags', ], 'minimum_input_length' => 2, 'required' => false, 'property' => 'name', 'multiple' => 'true', ]) ->add('text', 'textarea', [ 'attr' => ['class' => 'ckeditor'], ]) ->add('published', null, [ 'required' => false, ]) ->add('publishedAt', 'sonata_type_date_picker', [ 'required' => false, 'format' => 'dd MM y', ]) ->add('author') ->add('metaDescription', 'textarea', [ 'required' => false, ]) ->add('metaKeywords', 'text', [ 'required' => false, ]) ; }
{@inheritdoc}
entailment
public function getBundleInstance(KernelInterface $kernel) { if (!class_exists($this->name)) { throw new \LogicException(sprintf('The Symfony bundle "%s" does not exist.', $this->name)); } return new $this->name(); }
{@inheritdoc}
entailment
public function process(ContainerBuilder $container) { $definition = $container->getDefinition('twig'); $definition ->addMethodCall( 'addGlobal', ['image_previews_base_uri', $container->getParameter('harentius_blog.articles.image_previews_base_uri')] )->addMethodCall( 'addGlobal', ['default_locale', $container->getParameter('kernel.default_locale')] )->addMethodCall( 'addGlobal', ['sharethis_property', $container->getParameter('harentius_blog.articles.sharethis.property')] )->addMethodCall( 'addGlobal', ['sharethis_product', $container->getParameter('harentius_blog.articles.sharethis.product')] ) ; }
{@inheritdoc}
entailment
protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('name') ->add('slug', null, [ 'required' => false, ]) ->add('parent') ->add('metaDescription') ->add('metaKeywords') ; }
{@inheritdoc}
entailment
public function parse($resource, $type = null): array { @trigger_error('Using a bundles.json file has been deprecated and will no longer work in version 3.0. Use the Plugin::getBundles() method to define your bundles instead.', E_USER_DEPRECATED); $configs = []; $json = $this->parseJsonFile($resource); $this->parseBundles($json, $configs); return $configs; }
{@inheritdoc}
entailment
private function parseJsonFile(string $file): array { if (!is_file($file)) { throw new \InvalidArgumentException("$file is not a file"); } $json = json_decode(file_get_contents($file), true); if (null === $json) { throw new \RuntimeException("File $file cannot be decoded"); } return $json; }
Parses the file and returns the configuration array. @throws \InvalidArgumentException @throws \RuntimeException
entailment
private function parseBundles(array $bundles, array &$configs): void { foreach ($bundles as $options) { // Only one value given, must be class name if (!\is_array($options)) { $options = ['bundle' => $options]; } if (!isset($options['bundle'])) { throw new \RuntimeException( sprintf('Missing class name for bundle config (%s)', json_encode($options)) ); } if (!empty($options['optional']) && !class_exists($options['bundle'])) { continue; } $config = new BundleConfig($options['bundle']); if (isset($options['replace'])) { $config->setReplace($options['replace']); } if (isset($options['development'])) { if (true === $options['development']) { $config->setLoadInProduction(false); } elseif (false === $options['development']) { $config->setLoadInDevelopment(false); } } if (isset($options['load-after'])) { $config->setLoadAfter($options['load-after']); } $configs[] = $config; } }
Parses the bundle array and generates config objects. @throws \RuntimeException
entailment
protected function orderByDependencies(array $dependencies): array { $ordered = []; $available = array_keys($dependencies); while (0 !== \count($dependencies)) { $success = $this->doResolve($dependencies, $ordered, $available); if (false === $success) { throw new UnresolvableDependenciesException( "The dependencies order could not be resolved.\n".print_r($dependencies, true) ); } } return $ordered; }
Returns a list of array keys ordered by their dependencies. @throws UnresolvableDependenciesException @return string[]
entailment
private function doResolve(array &$dependencies, array &$ordered, array $available): bool { $failed = true; foreach ($dependencies as $name => $requires) { if (true === $this->canBeResolved($requires, $available, $ordered)) { $failed = false; $ordered[] = $name; unset($dependencies[$name]); } } return !$failed; }
Resolves the dependency order.
entailment
private function canBeResolved(array $requires, array $available, array $ordered): bool { if (0 === \count($requires)) { return true; } return 0 === \count(array_diff(array_intersect($requires, $available), $ordered)); }
Checks whether the requirements can be resolved.
entailment
public function preUpdate($object) { /** @var Article $object */ /** @var EntityManagerInterface $em */ $em = $this->getConfigurationPool()->getContainer()->get('doctrine.orm.entity_manager'); /** @var array $storedArticle */ $originalArticleData = $em->getUnitOfWork()->getOriginalEntityData($object); if (!$originalArticleData['published'] && $object->isPublished() && !$object->getPublishedAt()) { $object->setPublishedAt(new \DateTime()); } }
{@inheritdoc}
entailment
public function createQuery($context = 'list') { /** @var QueryBuilder $query */ $query = parent::createQuery($context); $alias = $query->getRootAliases()[0]; $query ->orderBy($alias . '.published', 'ASC') ->addOrderBy($alias . '.publishedAt', 'DESC') ; return $query; }
{@inheritdoc}
entailment
public function getExtensionConfig($name): array { $configs = parent::getExtensionConfig($name); $plugins = $this->pluginLoader->getInstancesOf(PluginLoader::EXTENSION_PLUGINS); /** @var ExtensionPluginInterface[] $plugins */ foreach ($plugins as $plugin) { $configs = $plugin->getExtensionConfig($name, $configs, $this); } return $configs; }
{@inheritdoc}
entailment
private function setLoadAfterLegacyModules(): void { static $legacy = [ 'core', 'calendar', 'comments', 'faq', 'listing', 'news', 'newsletter', ]; $modules = array_merge($legacy, [$this->getName()]); sort($modules); $modules = array_values($modules); array_splice($modules, array_search($this->getName(), $modules, true)); if (!\in_array('core', $modules, true)) { $modules[] = 'core'; } $this->setLoadAfter($modules); }
Adjusts the configuration so the module is loaded after the legacy modules.
entailment
public function build(ContainerBuilder $container) { parent::build($container); $container ->addCompilerPass(new SetTwigVariablesPass()) ->addCompilerPass(new LocalesConfigPass()) ; }
{@inheritdoc}
entailment
public function handle() { $this->copyConfigFile(); $this->copyStubsDirectory(); $this->updateStubsPathsInConfigFile(); $this->info("The config file has been copied to '" . $this->getConfigPath() . "'."); $this->info("The stubs have been copied to '{$this->option('path')}'."); }
Execute the command
entailment
private function copyConfigFile() { $path = $this->getConfigPath(); // if generatords config already exist if ($this->files->exists($path) && $this->option('force') === false) { $this->error("{$path} already exists! Run 'generate:publish-stubs --force' to override the config file."); die; } File::copy(__DIR__ . '/../config/config.php', $path); }
Copy the config file to the default config folder
entailment
private function copyStubsDirectory() { $path = $this->option('path'); // if controller stub already exist if ($this->files->exists($path . DIRECTORY_SEPARATOR . 'controller.stub') && $this->option('force') === false) { $this->error("Stubs already exists! Run 'generate:publish-stubs --force' to override the stubs."); die; } File::copyDirectory(__DIR__ . '/../../resources/stubs', $path); }
Copy the stubs directory
entailment
private function updateStubsPathsInConfigFile() { $updated = str_replace('vendor/bpocallaghan/generators/', '', File::get($this->getConfigPath())); File::put($this->getConfigPath(), $updated); }
Update stubs path in the new published config file
entailment
public function getStatus($ruc, $tipo, $serie, $numero) { return $this->getStatusResult('getStatus', 'status', $ruc, $tipo, $serie, $numero); }
Obtiene el estado del comprobante. @param string $ruc @param string $tipo @param string $serie @param int $numero @return StatusCdrResult
entailment
public function getStatusCdr($ruc, $tipo, $serie, $numero) { return $this->getStatusResult('getStatusCdr', 'statusCdr', $ruc, $tipo, $serie, $numero); }
Obtiene el CDR del comprobante. @param string $ruc @param string $tipo @param string $serie @param int $numero @return StatusCdrResult
entailment
public function getForms($offset = 0, $limit = 0, $filter = null, $orderby = null) { $params = $this->createConditions($offset, $limit, $filter, $orderby); return $this->_executeGetRequest('user/forms', $params); }
[getForms Get a list of forms for this account] @param [integer] $offset [Start of each result set for form list. (optional)] @param [integer] $limit [Number of results in each result set for form list. (optional)] @param [array] $filter [Filters the query results to fetch a specific form range.(optional)] @param [string] $orderBy [Order results by a form field name. (optional)] @return [array] [Returns basic details such as title of the form, when it was created, number of new and total submissions.]
entailment
public function getHistory($action = null, $date = null, $sortBy = null, $startDate = null, $endDate = null) { $params = $this->createHistoryQuery($action, $date, $sortBy, $startDate, $endDate); return $this->_executeGetRequest('user/history', $params); }
[getHistory Get user activity log] @param [enum] $action [Filter results by activity performed. Default is 'all'.] @param [enum] $date [Limit results by a date range. If you'd like to limit results by specific dates you can use startDate and endDate fields instead.] @param [enum] $sortBy [Lists results by ascending and descending order.] @param [string] $startDate [Limit results to only after a specific date. Format: MM/DD/YYYY.] @param [string] $endDate [Limit results to only before a specific date. Format: MM/DD/YYYY.] @return [array] [Returns activity log about things like forms created/modified/deleted, account logins and other operations.]
entailment
public function getFormSubmissions($formID, $offset = 0, $limit = 0, $filter = null, $orderby = null) { $params = $this->createConditions($offset, $limit, $filter, $orderby); return $this->_executeGetRequest("form/{$formID}/submissions", $params); }
[getFormSubmissions List of a form submissions] @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] @param [int] $offset [Start of each result set for form list. (optional)] @param [int] $limit [Number of results in each result set for form list. (optional)] @param [array] $filter [Filters the query results to fetch a specific form range.(optional)] @param [string] $orderBy [Order results by a form field name. (optional)] @return [array] [Returns submissions of a specific form.]
entailment
public function createFormSubmission($formID, $submission) { $sub = array(); foreach ($submission as $key => $value) { if (strpos($key, '_')) { $qid = substr($key, 0, strpos($key, '_')); $type = substr($key, strpos($key, '_') + 1); $sub["submission[{$qid}][{$type}]"] = $value; } else { $sub["submission[{$key}]"] = $value; } } return $this->_executePostRequest("form/{$formID}/submissions", $sub); }
[createFormSubmissions Submit data to this form using the API] @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] @param [array] $submission [Submission data with question IDs.] @return [array] [Returns posted submission ID and URL.]
entailment
public function editSubmission($sid, $submission) { $sub = array(); foreach ($submission as $key => $value) { if (strpos($key, '_') && $key != 'created_at') { $qid = substr($key, 0, strpos($key, '_')); $type = substr($key, strpos($key, '_') + 1); $sub["submission[{$qid}][{$type}]"] = $value; } else { $sub["submission[{$key}]"] = $value; } } return $this->_executePostRequest("submission/".$sid, $sub); }
[editSubmission Edit a single submission] @param [integer] $sid [You can get submission IDs when you call /form/{id}/submissions.] @param [array] $submission [New submission data with question IDs.] @return [array] [Returns status of request.]
entailment
public function createFormQuestion($formID, $question) { $params = array(); foreach ($question as $key => $value) { $params["question[{$key}]"] = $value; } return $this->_executePostRequest("form/{$formID}/questions", $params); }
[createFormQuestion Add new question to specified form] @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] @param [array] $question [New question properties like type and text.] @return [array] [Returns properties of new question.]
entailment
public function editFormQuestion($formID, $qid, $questionProperties) { $question = array(); foreach ($questionProperties as $key => $value) { $question["question[{$key}]"] = $value; } return $this->_executePostRequest("form/{$formID}/question/{$qid}", $question); }
[editFormQuestion Add or edit a single question properties] @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] @param [integer] $qid [Identifier for each question on a form. You can get a list of question IDs from /form/{id}/questions.] @param [array] $questionProperties [New question properties like text and order.] @return [array] [Returns edited property and type of question.]
entailment
public function setFormProperties($formID, $formProperties) { $properties = array(); foreach ($formProperties as $key => $value) { $properties["properties[{$key}]"] = $value; } return $this->_executePostRequest("form/{$formID}/properties", $properties); }
[setFormProperties Add or edit properties of a specific form] @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] @param [array] $formProperties [New properties like label width.] @return [array] [Returns edited properties.]
entailment
public function createForm($form) { $params = array(); foreach ($form as $key => $value) { foreach ($value as $k => $v) { if ($key == "properties") { $params["{$key}[{$k}]"] = $v; } else { foreach ($v as $a => $b) { $params["{$key}[{$k}][{$a}]"] = $b; } } } } return $this->_executePostRequest('user/forms', $params); }
[createForm Create a new form] @param [array] $form [Questions, properties and emails of new form.] @return [array] [Returns new form.]
entailment
public function handle() { parent::handle(); if ($this->option('migration')) { $name = $this->getMigrationName(); $this->call('generate:migration', [ 'name' => $name, '--model' => false, '--schema' => $this->option('schema') ]); } }
Execute the console command. @return void
entailment
public function add($group_id, $phone, $params = array()) { $params = array_merge(array( 'group_id' => $group_id, 'phone' => $phone, ), $params); return $this->master->call('contacts/add', $params); }
Add new contact @param int|array $group_id @param string $phone @param array $params @option string "email" @option string "first_name" @option string "last_name" @option string "company" @option string "tax_id" @option string "address" @option string "city" @option string "description" @return object @option bool "success" @option int "id"
entailment
public function index($group_id = null, $search = null, $params = array()) { $params = array_merge(array( 'group_id' => $group_id, 'search' => $search ), $params); return $this->master->call('contacts/index', $params); }
List of contacts @param int $group_id @param string $search @param array $params @option int "page" The number of the displayed page @option int "limit" Limit items are displayed on the single page @option string "sort" Values: first_name|last_name|phone|company|tax_id|email|address|city|description @option string "order" Values: asc|desc @return object @option array "paging" @option int "page" The number of current page @option int "count" The number of all pages @options array "items" @option int "id" @option string "phone" @option string "email" @option string "company" @option string "first_name" @option string "last_name" @option string "tax_id" @option string "address" @option string "city" @option string "description" @option bool "blacklist" @option int "group_id" @option string "group_name"
entailment
public function edit($id, $group_id, $phone, $params = array()) { $params = array_merge(array( 'id' => $id, 'group_id' => $group_id, 'phone' => $phone ), $params); return $this->master->call('contacts/edit', $params); }
Editing a contact @param int $id @param int|array $group_id @param string $phone @param array $params @option string "email" @option string "first_name" @option string "last_name" @option string "company" @option string "tax_id" @option string "address" @option string "city" @option string "description" @return object @option bool "success" @option int "id"
entailment
public function import($group_name, $contact) { $params = array( 'group_name' => $group_name, 'contact' => $contact ); return $this->master->call('contacts/import', $params); }
Import contact list @param string $group_name @param array $contact[] @option string "phone" @option string "email" @option string "first_name" @option string "last_name" @option string "company" @return object @option bool "success" @option int "id" @option int "correct" Number of contacts imported correctly @option int "failed" Number of errors
entailment
public function expectExplicit($expectedTag = null): ExplicitTagging { $el = $this; if (!$el instanceof ExplicitTagging) { throw new \UnexpectedValueException( "Element doesn't implement explicit tagging."); } if (isset($expectedTag)) { $el->expectTagged($expectedTag); } return $el; }
Check whether element supports explicit tagging. @param int|null $expectedTag Optional outer tag expectation @throws \UnexpectedValueException If expectation fails @return ExplicitTagging
entailment
public function expectImplicit($expectedTag = null): ImplicitTagging { $el = $this; if (!$el instanceof ImplicitTagging) { throw new \UnexpectedValueException( "Element doesn't implement implicit tagging."); } if (isset($expectedTag)) { $el->expectTagged($expectedTag); } return $el; }
Check whether element supports implicit tagging. @param int|null $expectedTag Optional outer tag expectation @throws \UnexpectedValueException If expectation fails @return ImplicitTagging
entailment
public function asImplicit(int $tag, $expectedTag = null, int $expectedClass = Identifier::CLASS_UNIVERSAL): UnspecifiedType { return $this->expectImplicit($expectedTag)->implicit($tag, $expectedClass); }
Get the wrapped inner element employing implicit tagging. @param int $tag Type tag of the inner element @param int|null $expectedTag Optional outer tag expectation @param int $expectedClass Optional inner type class expectation @throws \UnexpectedValueException If expectation fails @return UnspecifiedType
entailment
public function intVal(): int { if (!isset($this->_intNum)) { $num = gmp_init($this->_num, 10); if (gmp_cmp($num, $this->_intMaxGmp()) > 0) { throw new \RuntimeException("Integer overflow."); } if (gmp_cmp($num, $this->_intMinGmp()) < 0) { throw new \RuntimeException("Integer underflow."); } $this->_intNum = gmp_intval($num); } return $this->_intNum; }
Get the number as an integer. @throws \RuntimeException If number overflows integer size @return int
entailment
public function handle() { $provider = $this->laravel->getProvider(EventServiceProvider::class); foreach ($provider->listens() as $event => $listeners) { $this->makeEventAndListeners($event, $listeners); } $this->info('Events and listeners generated successfully!'); }
Execute the console command. @return void
entailment
protected function makeEventAndListeners($event, $listeners) { if (! Str::contains($event, '\\')) { return; } $this->call('generate:event', ['name' => $event]); $this->makeListeners($event, $listeners); }
Make the event and listeners for the given event. @param string $event @param array $listeners @return void
entailment
protected function makeListeners($event, $listeners) { foreach ($listeners as $listener) { $listener = preg_replace('/@.+$/', '', $listener); $this->call('generate:listener', ['name' => $listener, '--event' => $event]); } }
Make the listeners for the given event. @param string $event @param array $listeners @return void
entailment
public function sendSms($phone, $text, $sender = null, $params = array()) { $params = array_merge(array( 'phone' => $phone, 'text' => $text, 'sender' => $sender ), $params); return $this->master->call('messages/send_sms', $params); }
Sending messages @param string|array $phone @param string $text Message @param string $sender Sender name only for FULL SMS @param array $params @option bool "details" Show details of messages @option bool "utf" Change encoding to UTF-8 (Only for FULL SMS) @option bool "flash" @option bool "speed" Priority canal only for FULL SMS @option bool "test" Test mode @option bool "vcard" vCard message @option string "wap_push" WAP Push URL address @option string "date" Set the date of sending @option int|array "group_id" Sending to the group instead of a phone number @option int|array "contact_id" Sending to phone from contacts @option string|array "unique_id" Own identifiers of messages @return object @option bool "success" @option int "queued" Number of queued messages @option int "unsent" Number of unsent messages @option object "items" @option string "id" @option string "phone" @option string "status" - queued|unsent @option string "queued" Date of enqueued @option int "parts" Number of parts a message @option int "error_code" @option string "error_message" @option string "text"
entailment
public function sendPersonalized($messages, $sender = null, $params = array()) { $params = array_merge(array( 'messages' => $messages, 'sender' => $sender ), $params); return $this->master->call('messages/send_personalized', $params); }
Sending personalized messages @param array $messages @option string "phone" @option string "text" @param string $sender Sender name only for FULL SMS @param array $params @option bool "details" Show details of messages @option bool "utf" Change encoding to UTF-8 (only for FULL SMS) @option bool "flash" @option bool "speed" Priority canal only for FULL SMS @option bool "test" Test mode @option string "date" Set the date of sending @option int|array "group_id" Sending to the group instead of a phone number @option string "text" Message if is set group_id @option string|array "uniqe_id" Own identifiers of messages @option bool "voice" Send VMS @return object @option bool "success" @option int "queued" Number of queued messages @option int "unsent" Number of unsent messages @option object "items" @option string "id" @option string "phone" @option string "status" - queued|unsent @option string "queued" Date of enqueued @option int "parts" Number of parts a message @option int "error_code" @option string "error_message" @option string "text"
entailment
public function sendVoice($phone, $params = array()) { $params = array_merge(array( 'phone' => $phone ), $params); return $this->master->call('messages/send_voice', $params); }
Sending Voice message @param string|array $phone @param array $params @option string "text" If send of text to voice @option string "file_id" ID from wav files @option string "date" Set the date of sending @option bool "test" Test mode @option int|array "group_id" Sending to the group instead of a phone number @option int|array "contact_id" Sending to phone from contacts @return object @option bool "success" @option int "queued" Number of queued messages @option int "unsent" Number of unsent messages @option object "items" @option string "id" @option string "phone" @option string "status" - queued|unsent @option string "queued" Date of enqueued @option int "parts" Number of parts a message @option int "error_code" @option string "error_message" @option string "text"
entailment
public function sendMms($phone, $title, $params = array()) { $params = array_merge(array( 'phone' => $phone, 'title' => $title ), $params); return $this->master->call('messages/send_mms', $params); }
Sending MMS @param string|array $phone @param string $title Title of message (max 40 chars) @param array $params @option string "file_id" @option string|array "file" File in base64 encoding @option string "date" Set the date of sending @option bool "test" Test mode @option int|array "group_id" Sending to the group instead of a phone number @return object @option bool "success" @option int "queued" Number of queued messages @option int "unsent" Number of unsent messages @option object "items" @option string "id" @option string "phone" @option string "status" - queued|unsent @option string "queued" Date of enqueued @option int "parts" Number of parts a message @option int "error_code" @option string "error_message" @option string "text"
entailment
public function view($id, $params = array()) { $params = array_merge(array('id' => $id), $params); return $this->master->call('messages/view', $params); }
View single message @param string $id @param array $params @option string "unique_id" @option bool "show_contact" Show details of the recipient from the contacts @return object @option string "id" @option string "phone" @option string "status" - delivered: The message is sent and delivered - undelivered: The message is sent but not delivered - sent: The message is sent and waiting for report - unsent: The message wasn't sent - in_progress: The message is queued for sending - saved: The message was saved in schedule @option string "queued" Date of enqueued @option string "sent" Date of sending @option string "delivered" Date of deliver @option string "sender" @option string "type" - eco|full|mms|voice @option string "text" @option string "reason" - message_expired - unsupported_number - message_rejected - missed_call - wrong_number - limit_exhausted - lock_send - wrong_message - operator_error - wrong_sender_name - number_is_blacklisted - sending_to_foreign_networks_is_locked - no_permission_to_send_messages - other_error @option object "contact" @option string "first_name" @option string "last_name" @option string "company" @option string "phone" @option string "email" @option string "tax_id" @option string "city" @option string "address" @option string "description"
entailment
public function delete($id, $unique_id = null) { $params = array('id' => $id, 'unique_id' => $unique_id); return $this->master->call('messages/delete', $params); }
Deleting message from the scheduler @param string|array $id @param string|array $unique_id @return object @option bool "success"
entailment
public function recived($type, $params = array()) { $params = array_merge(array('type' => $type), $params); return $this->master->call('messages/recived', $params); }
List of received messages @param string $type - eco SMS ECO replies - nd Incoming messages to ND number - ndi Incoming messages to ND number - mms Incoming MMS @param array $params @option string "ndi" Filtering by NDI @option string|array "phone" Filtering by phone @option string "date_from" The scope of the initial @option string "date_to" The scope of the final @option bool "read" Mark as read @option int "page" The number of the displayed page @option int "limit" Limit items are displayed on the single page @option string "order" asc|desc @return object @option object "paging" @option int "page" The number of current page @option int "count" The number of all pages @option object "items" @option int "id" @option string "type" eco|nd|ndi|mms @option string "phone" @option string "recived" Date of received message @option string "message_id" ID of outgoing message (only for ECO SMS) @option bool "blacklist" Is the phone is blacklisted? @option string "text" Message @option string "to_number" Number of the recipient (for MMS) @option string "title" Title of message (for MMS) @option object "attachments" (for MMS) @option int "id" @option string "name" @option string "content_type" @option string "data" File @option object "contact" @option string "first_name" @option string "last_name" @option string "company" @option string "phone" @option string "email" @option string "tax_id" @option string "city" @option string "address" @option string "description"
entailment
public function sendNd($phone, $text) { $params = array( 'phone' => $phone, 'text' => $text ); return $this->master->call('messages/send_nd', $params); }
Sending a message to an ND/SC @param string $phone Sender phone number @param string $text Message @return object @option bool "success"
entailment
public function sendNdi($phone, $text, $ndi_number) { $params = array( 'phone' => $phone, 'text' => $text, 'ndi_number' => $ndi_number ); return $this->master->call('messages/send_ndi', $params); }
Sending a message to an NDI/SCI @param string $phone Sender phone number @param string $text Message @param string $ndi_number Recipient phone number @return object @option bool "success"
entailment
public function build($type) { if (!is_subclass_of($type, BaseSunat::class)) { throw new \Exception($type.' should be instance of '.BaseSunat::class); } /** @var $service BaseSunat */ $service = new $type(); $service->setClient($this->client); return $service; }
@param string $type Service Class @return object @throws \Exception
entailment
public function getData() { $this->validate('amount', 'token'); $data = array(); $data['token'] = $this->getToken(); $data['amount'] = $this->getAmountInteger(); $data['currencyCode'] = $this->getCurrency(); $data['orderDescription'] = $this->getDescription(); $data['customerOrderCode'] = $this->getTransactionId(); $data['currency'] = $this->getCurrency(); $card = $this->getCard(); if ($card) { $data['billingAddress'] = array(); $data['billingAddress']['address1'] = $card->getBillingAddress1(); $data['billingAddress']['address2'] = $card->getBillingAddress2(); $data['billingAddress']['city'] = $card->getBillingCity(); $data['billingAddress']['state'] = $card->getBillingState(); $data['billingAddress']['countryCode'] = $card->getBillingCountry(); $data['billingAddress']['postalCode'] = $card->getBillingPostcode(); $data['billingAddress']['telephoneNumber'] = $card->getBillingPhone(); $data['name'] = $card->getName(); $data['deliveryAddress'] = array(); $data['deliveryAddress']['firstName'] = $card->getShippingFirstName(); $data['deliveryAddress']['lastName'] = $card->getShippingLastName(); $data['deliveryAddress']['address1'] = $card->getShippingAddress1(); $data['deliveryAddress']['address2'] = $card->getShippingAddress2(); $data['deliveryAddress']['city'] = $card->getShippingCity(); $data['deliveryAddress']['state'] = $card->getShippingState(); $data['deliveryAddress']['countryCode'] = $card->getShippingCountry(); $data['deliveryAddress']['postalCode'] = $card->getShippingPostcode(); $data['deliveryAddress']['telephoneNumber'] = $card->getBillingPhone(); $data['shopperEmailAddress'] = $card->getEmail(); } $data['shopperIpAddress'] = $this->getClientIp(); // Omnipay does not support recurring at the moment $data['orderType'] = 'ECOM'; return $data; }
Set up the base data for a purchase request @return mixed[]
entailment
public function decompress($content, callable $filter = null) { $temp = tempnam(sys_get_temp_dir(), time().'.zip'); file_put_contents($temp, $content); $zip = new \ZipArchive(); $output = []; if (true === $zip->open($temp) && $zip->numFiles > 0) { $output = iterator_to_array($this->getFiles($zip, $filter)); } $zip->close(); unlink($temp); return $output; }
Extract files. @param string $content @param callable|null $filter @return array
entailment
public function index($phone = null, $params = array()) { $params = array_merge(array('phone' => $phone), $params); return $this->master->call('blacklist/index', $params); }
List of blacklist phones @param string $phone @param array $params @option int "page" The number of the displayed page @option int "limit" Limit items are displayed on the single page @return object @option array "paging" @option int "page" The number of current page @option int "count" The number of all pages @option array "items" @option string "phone" @option string "added" Date of adding phone
entailment
public function register() { // merge config $configPath = __DIR__ . '/config/config.php'; $this->mergeConfigFrom($configPath, 'generators'); // register all the artisan commands $this->registerCommand(PublishCommand::class, 'publish'); $this->registerCommand(ModelCommand::class, 'model'); $this->registerCommand(ViewCommand::class, 'view'); $this->registerCommand(ControllerCommand::class, 'controller'); $this->registerCommand(MigrationCommand::class, 'migration'); $this->registerCommand(MigrationPivotCommand::class, 'migrate.pivot'); $this->registerCommand(SeedCommand::class, 'seed'); $this->registerCommand(NotificationCommand::class, 'notification'); $this->registerCommand(EventCommand::class, 'event'); $this->registerCommand(ListenerCommand::class, 'listener'); $this->registerCommand(EventGenerateCommand::class, 'event.generate'); $this->registerCommand(TraitCommand::class, 'trait'); $this->registerCommand(RepositoryCommand::class, 'repository'); $this->registerCommand(ContractCommand::class, 'contract'); $this->registerCommand(JobCommand::class, 'job'); $this->registerCommand(ConsoleCommand::class, 'console'); $this->registerCommand(MiddlewareCommand::class, 'middleware'); $this->registerCommand(ResourceCommand::class, 'resource'); $this->registerCommand(FileCommand::class, 'file'); }
Register the service provider. @return void
entailment
private function registerCommand($class, $command) { $this->app->singleton($this->commandPath . $command, function ($app) use ($class) { return $app[$class]; }); $this->commands($this->commandPath . $command); }
Register a singleton command @param $class @param $command
entailment
private function getFileName() { $name = $this->getArgumentNameOnly(); switch ($this->option('type')) { case 'view': break; case 'model': $name = $this->getModelName(); break; case 'controller': $name = $this->getControllerName($name); break; case 'seed': $name = $this->getSeedName($name); break; } // overide the name if ($this->option('name')) { return $this->option('name') . $this->settings['file_type']; } return $this->settings['prefix'] . $name . $this->settings['postfix'] . $this->settings['file_type']; }
Get the filename of the file to generate @return string
entailment
protected function getPath($name) { $name = $this->getFileName(); $withName = boolval($this->option('name')); $path = $this->settings['path']; if ($this->settingsDirectoryNamespace() === true) { $path .= $this->getArgumentPath($withName); } $path .= $name; return $path; }
Get the destination class path. @param string $name @return string
entailment
protected function buildClass($name) { $stub = $this->files->get($this->getStub()); // examples used for the placeholders is for 'foo.bar' // App\Foo $stub = str_replace('{{namespace}}', $this->getNamespace($name), $stub); // App\ $stub = str_replace('{{rootNamespace}}', $this->getAppNamespace(), $stub); // Bar $stub = str_replace('{{class}}', $this->getClassName(), $stub); $url = $this->getUrl(); // /foo/bar // /foo/bar $stub = str_replace('{{url}}', $this->getUrl(), $stub); // bars $stub = str_replace('{{collection}}', $this->getCollectionName(), $stub); // Bars $stub = str_replace('{{collectionUpper}}', $this->getCollectionUpperName(), $stub); // Bar $stub = str_replace('{{model}}', $this->getModelName(), $stub); // Bar $stub = str_replace('{{resource}}', $this->resource, $stub); // bar $stub = str_replace('{{resourceLowercase}}', $this->resourceLowerCase, $stub); // ./resources/views/foo/bar.blade.php $stub = str_replace('{{path}}', $this->getPath(''), $stub); // foos.bars $stub = str_replace('{{view}}', $this->getViewPath($this->getUrl(false)), $stub); // bars $stub = str_replace('{{table}}', $this->getTableName($url), $stub); // event - listeners $event = $this->option('event'); if (!Str::startsWith($event, $this->laravel->getNamespace()) && !Str::startsWith($event, 'Illuminate') ) { $event = $this->laravel->getNamespace() . 'Events\\' . $event; } // event class name $stub = str_replace('{{event}}', class_basename($event), $stub); // event with namespace $stub = str_replace('{{eventAndNamespace}}', $event, $stub); return $stub; }
Build the class with the given name. @param string $name @return string
entailment
protected function getNamespace($name, $withApp = true) { $path = (strlen($this->settings['namespace']) >= 2 ? $this->settings['namespace'] . '\\' : ''); // dont add the default namespace if specified not to in config if ($this->settingsDirectoryNamespace() === true) { $path .= str_replace('/', '\\', $this->getArgumentPath()); } $pieces = array_map('ucfirst', explode('/', $path)); $namespace = ($withApp === true ? $this->getAppNamespace() : '') . implode('\\', $pieces); $namespace = rtrim(ltrim(str_replace('\\\\', '\\', $namespace), '\\'), '\\'); return $namespace; }
Get the full namespace name for a given class. @param string $name @param bool $withApp @return string
entailment
protected function getUrl($lowercase = true) { if ($lowercase) { $url = '/' . rtrim(implode('/', array_map('snake_case', explode('/', $this->getArgumentPath(true)))), '/'); $url = (implode('/', array_map('str_slug', explode('/', $url)))); return $url; } return '/' . rtrim(implode('/', explode('/', $this->getArgumentPath(true))), '/'); }
Get the url for the given name @param bool $lowercase @return string
entailment
public function loadXpathFromDoc(\DOMDocument $doc) { $docName = $doc->documentElement->localName; $this->root = '/'.self::ROOT_PREFIX.':'.$docName; $this->xpath = new \DOMXPath($doc); $this->xpath->registerNamespace(self::ROOT_PREFIX, $doc->documentElement->namespaceURI); }
Init XPath from document. @param \DOMDocument $doc
entailment
public function getValue($query) { $nodes = $this->xpath->query($this->root.'/'.$query); if ($nodes->length > 0) { return $nodes->item(0)->nodeValue; } return null; }
* Get value from first node result. @param string $query relative to root namespace @return null|string
entailment
public function handle() { $this->resource = $this->getResourceOnly(); $this->settings = config('generators.defaults'); $this->callModel(); $this->callView(); $this->callRepository(); $this->callController(); $this->callMigration(); $this->callSeed(); $this->callMigrate(); // confirm dump autoload if ($this->confirm("Run 'composer dump-autoload'?")) { $this->composer->dumpAutoloads(); } $this->info('All Done!'); $this->info('Remember to add ' . "`Route::resource('" . str_replace('_', '-', $this->getCollectionName()) . "', '" . $this->getResourceControllerName() . "');`" . ' in `routes\\web.php`'); }
Execute the console command. @return void
entailment
private function callModel() { $name = $this->getModelName(); $resourceString = $this->getResourceOnly(); $resourceStringLength = strlen($this->getResourceOnly()); if ($resourceStringLength > 18) { $ans = $this->confirm("Your resource {$resourceString} may have too many characters to use for many to many relationships. The length is {$resourceStringLength}. Continue?"); if ($ans === false) { echo "generate:resource cancelled!"; die; } } if ($this->confirm("Create a $name model?")) { $this->callCommandFile('model'); } }
Call the generate:model command
entailment
private function callView() { if ($this->confirm("Create crud views for the $this->resource resource?")) { $views = config('generators.resource_views'); foreach ($views as $key => $name) { $resource = $this->argument('resource'); if (str_contains($resource, '.')) { $resource = str_replace('.', '/', $resource); } $this->callCommandFile('view', $this->getViewPath($resource), $key, ['--name' => $name]); } } }
Generate the resource views
entailment
private function callRepository() { // check the config if (config('generators.settings.controller.repository_contract')) { if ($this->confirm("Create a reposity and contract for the $this->resource resource?")) { $name = $this->getModelName(); $this->repositoryContract = true; $this->callCommandFile('contract', $name); $this->callCommandFile('repository', $name); //$contract = $name . config('generators.settings.contract.postfix'); //$this->callCommandFile('repository', $name, ['--contract' => $contract]); } } }
Generate the Repository / Contract Pattern files
entailment
private function callController() { $name = $this->getResourceControllerName(); if ($this->confirm("Create a controller ($name) for the $this->resource resource?")) { $arg = $this->getArgumentResource(); $name = substr_replace($arg, str_plural($this->resource), strrpos($arg, $this->resource), strlen($this->resource)); if ($this->repositoryContract) { $this->callCommandFile('controller', $name, 'controller_repository'); } else { // if admin - update stub if (!str_contains($name, 'admin.')) { $this->callCommandFile('controller', $name, 'controller'); } else { $this->callCommandFile('controller', $name, 'controller_admin'); } } } }
Generate the resource controller
entailment
private function callMigration() { $name = $this->getMigrationName($this->option('migration')); if ($this->confirm("Create a migration ($name) for the $this->resource resource?")) { $this->callCommand('migration', $name, [ '--model' => false, '--schema' => $this->option('schema') ]); } }
Call the generate:migration command
entailment
private function callCommandFile($type, $name = null, $stub = null, $options = []) { $this->call('generate:file', array_merge($options, [ 'name' => ($name ? $name : $this->argument('resource')), '--type' => $type, '--force' => $this->optionForce(), '--plain' => $this->optionPlain(), '--stub' => ($stub ? $stub : $this->optionStub()), ])); }
Call the generate:file command to generate the given file @param $type @param null $name @param null $stub @param array $options
entailment
private function getArgumentResource() { $name = $this->argument('resource'); if (str_contains($name, '/')) { $name = str_replace('/', '.', $name); } if (str_contains($name, '\\')) { $name = str_replace('\\', '.', $name); } // lowecase and singular $name = strtolower(str_singular($name)); return $name; }
The resource argument Lowercase and singular each word @return array|mixed|string
entailment