sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function import(GitRepositoryEntity $gitRepository) { $importer = $this->app->make(TranslatableImporter::class); $fetcher = $this->app->make(Fetcher::class, ['gitRepository' => $gitRepository]); $packagesRepo = $this->app->make(PackageRepository::class); $package = $packagesRepo->findOneBy(['handle' => $gitRepository->getPackageHandle()]); if ($package === null) { if ($this->logger !== null) { $this->logger->notice(t('Creating new package with handle %s', $gitRepository->getPackageHandle())); } $package = PackageEntity::create($gitRepository->getPackageHandle()); $this->em->persist($package); $this->em->flush($package); } if ($this->logger !== null) { $this->logger->debug(t('Cloning/fetching repository')); } $fetcher->update(); if ($this->logger !== null) { $this->logger->debug(t('Listing tags')); } $taggedVersions = $fetcher->getTaggedVersions(); foreach ($taggedVersions as $tag => $version) { if ($gitRepository->getDetectedVersion($version) === null) { $gitRepository->addDetectedVersion($version, 'tag', $tag); $this->em->persist($gitRepository); $this->em->flush($gitRepository); } $packageVersion = null; foreach ($package->getVersions() as $pv) { if ($pv->getVersion() === $version) { $packageVersion = $pv; break; } } if ($packageVersion === null) { if ($this->logger !== null) { $this->logger->debug(t('Checking out tag %s', $tag, $version)); } $fetcher->switchToTag($tag); if ($this->logger !== null) { $this->logger->info(t('Extracting strings from tag %1$s for version %2$s', $tag, $version)); } $importer->importDirectory($fetcher->getRootDirectory(), $package->getHandle(), $version, ''); } else { if ($this->logger !== null) { $this->logger->debug(t('Tag already imported: %1$s (version: %2$s)', $tag, $version)); } } } foreach ($gitRepository->getDevBranches() as $branch => $version) { if ($gitRepository->getDetectedVersion($version) === null) { $gitRepository->addDetectedVersion($version, 'branch', $branch); $this->em->persist($gitRepository); $this->em->flush($gitRepository); } if ($this->logger !== null) { $this->logger->debug(t('Checking out development branch %s', $branch)); } $fetcher->switchToBranch($branch); if ($this->logger !== null) { $this->logger->info(t('Extracting strings from development branch %1$s for version %2$s', $branch, $version)); } $importer->importDirectory($fetcher->getRootDirectory(), $package->getHandle(), $version, ''); } }
Import the strings from a git repository.
entailment
protected function normalizeArgs(array $args) { $error = $this->app->make('helper/validation/error'); $normalized = []; $normalized['territoryRequestLevel'] = null; if (isset($args['territoryRequestLevel']) && (is_int($args['territoryRequestLevel']) || (is_string($args['territoryRequestLevel']) && is_numeric($args['territoryRequestLevel'])))) { $i = (int) $args['territoryRequestLevel']; switch ($i) { case self::TERRITORYREQUESTLEVEL_NEVER: case self::TERRITORYREQUESTLEVEL_OPTIONAL: case self::TERRITORYREQUESTLEVEL_NOTSOOPTIONAL: case self::TERRITORYREQUESTLEVEL_ALWAYS: $normalized['territoryRequestLevel'] = $i; break; } } if ($normalized['territoryRequestLevel'] === null) { $error->add(t('Please specify if and how the territory should be required')); } return $error->has() ? $error : $normalized; }
{@inheritdoc} @see BlockController::normalizeArgs()
entailment
private function startStep($checkToken = null) { if ($this->getAccess()->isLoggedIn()) { $result = true; $token = $this->app->make('token'); if ($checkToken !== null && !$token->validate($checkToken)) { $this->set('showError', $token->getErrorMessage()); $this->action_language(); $result = false; } else { $this->set('token', $this->app->make('token')); $this->set('form', $this->app->make('helper/form')); } } else { $result = false; $this->set('step', null); $this->set('showError', t('You need to sign-in in order to ask the creation of a new Translation Team')); } return $result; }
@param null|string $checkToken @return bool
entailment
private function checkExistingLocale($localeID) { $result = null; $localeRepo = $this->app->make(LocaleRepository::class); $existing = $localeRepo->find($localeID); if ($existing !== null) { if ($existing->isSource()) { $result = t("There couldn't be a language team for '%s' since it's the source language", $existing->getDisplayName()); } elseif ($existing->isApproved()) { $result = t("The language team for '%s' already exists", $existing->getDisplayName()); } elseif ($existing->getRequestedOn() !== null) { $result = t( "The language team for '%1\$s' has already been requested on %2\$s", $existing->getDisplayName(), $this->app->make('date')->formatDateTime($existing->getRequestedOn(), true) ); } else { $result = t("The language team for '%s' has already been requested", $existing->getDisplayName()); } } return $result; }
@param string $localeID @return string|null
entailment
private function createLocale($localeID, $notes, $approve) { $locale = LocaleEntity::create($localeID) ->setRequestedBy($this->getAccess()->getUserEntity('current')) ->setRequestedOn(new DateTime()) ->setIsApproved($approve) ; $em = $this->app->make(EntityManager::class); $em->persist($locale); $em->flush($locale); if (!$approve) { $this->app->make(NotificationRepository::class)->newLocaleRequested($locale, $notes); } return $locale; }
@param string $localeID @param string $notes @param bool $approve @return LocaleEntity
entailment
private function readCSVLine($fd) { for (; ;) { $line = @fgetcsv($fd, 0, ',', '"'); if ($line === false) { break; } if ($line === null) { throw new Exception('Error in CSV file'); } yield $line; } }
@param resource $fd @return array[array]
entailment
private function parseMap(OutputInterface $output, array $line) { $output->write('Parsing CSV header... '); $map = []; $testLocales = []; $numFields = 0; $sourceFieldsFound = 0; $m = null; foreach ($line as $index => $field) { if ($index !== $numFields) { throw new Exception('Invalid field index: ' . $index); } if (strpos($field, ',') !== false) { throw new Exception('Invalid field name: ' . $field); } if (isset($this->sourceFields[$field])) { ++$sourceFieldsFound; $key = $this->sourceFields[$field]; } elseif (preg_match($this->rxLocalizedFields, $field, $m)) { $mappedField = $this->localizedFields[$m[1]]; $mappedLocale = $m[2]; if (!isset($testLocales[$mappedLocale])) { $testLocales[$mappedLocale] = []; } $testLocales[$mappedLocale][] = $mappedField; $key = $mappedLocale . ',' . $mappedField; } else { throw new Exception('Unknown field #' . ($index + 1) . ': ' . $field); } if (in_array($key, $map, true)) { throw new Exception('Duplicated field: ' . $field); } $map[$index] = $key; ++$numFields; } if ($sourceFieldsFound !== count($this->sourceFields)) { throw new Exception('Bad source fields count'); } foreach ($testLocales as $id => $fields) { if (count($fields) !== count($this->localizedFields)) { throw new Exception('Bad fields count for locale ' . $id); } } $output->writeln('<info>done</info>'); $this->map = $map; $this->numFields = $numFields; }
@param array $line @return array
entailment
public function postPersist(LifecycleEventArgs $args) { $entity = $args->getObject(); if ($entity instanceof PackageVersionEntity) { $this->refreshPackageLatestVersion($args->getObjectManager(), $entity->getPackage()); } }
Callback method called when a new entity has been saved. @param LifecycleEventArgs $args
entailment
public function postUpdate(LifecycleEventArgs $args) { $entity = $args->getObject(); if ($entity instanceof PackageVersionEntity) { $em = $args->getObjectManager(); /* @var \Doctrine\ORM\EntityManager $em */ $unitOfWork = $em->getUnitOfWork(); $changeSet = $unitOfWork->getEntityChangeSet($entity); if (in_array('version', $changeSet)) { $this->refreshPackageLatestVersion($em, $entity->getPackage()); } } }
Callback method called when a modified entity is going to be saved. @param LifecycleEventArgs $args
entailment
public static function get($objectOrClass, $hook) { foreach (self::$hooks[$hook]['_global'] ?? [] as $callback) { yield $callback; } $class = is_object($objectOrClass) ? get_class($objectOrClass) : (string) $objectOrClass; foreach (self::$hooks[$hook][$class] ?? [] as $callback) { yield $callback; } if (is_object($objectOrClass)) { foreach (self::$hooks[$hook][self::getHookId($objectOrClass)] ?? [] as $callback) { yield $callback; } } }
@param object $objectOrClass @param string $hook @return \Traversable|\Closure[]
entailment
public static function getHookId($object) { return (function($object) { if (false == property_exists($object, 'hookId')) { $object->hookId = null; } if (false == $object->hookId) { $object->hookId = get_class($object).':'.uniqid('', true); } return $object->hookId; })->call($object, $object); }
@param object $object @return string
entailment
public function getByLocale(LocaleEntity $locale) { $app = Application::getFacadeApplication(); $result = $this->find($locale); if ($result === null) { $em = $this->getEntityManager(); try { $numTranslatable = (int) $app->make(TranslatableRepository::class) ->createQueryBuilder('t') ->select('count(t.id)') ->getQuery()->getSingleScalarResult(); } catch (NoResultException $x) { $numTranslatable = 0; } if ($numTranslatable === 0) { $numApprovedTranslations = 0; } else { try { $numApprovedTranslations = (int) $app->make(TranslationRepository::class) ->createQueryBuilder('t') ->select('count(t.id)') ->where('t.locale = :locale')->setParameter('locale', $locale) ->andWhere('t.current = 1') ->getQuery()->getSingleScalarResult(); } catch (NoResultException $x) { $numApprovedTranslations = 0; } } $result = LocaleStatsEntity::create($locale, $numTranslatable, $numApprovedTranslations); $em->persist($result); $em->flush($result); } return $result; }
Get the stats for a specific locale. If the stats does not exist yet, they are created. @return LocaleStatsEntity
entailment
public function resetForLocale(LocaleEntity $locale) { $this->createQueryBuilder('t') ->delete() ->where('t.locale = :locale')->setParameter('locale', $locale) ->getQuery()->execute(); }
Clear the stats for a specific locale. @para LocaleEntity $locale
entailment
protected function getGroup($name, $parent = null) { $name = trim($name, '/'); if ($parent === null || $parent === false || $parent === '') { $parent = null; $path = '/' . $name; } else { if (!$parent instanceof Group) { $parent = $this->getGroup($parent); } $path = '/' . $parent->getGroupName() . '/' . $name; } $result = \Group::getByPath($path); if (!$result) { $result = \Group::add($name, '', $parent, $this->getPackage()); if (!$result) { if ($parent) { throw new UserMessageException(t("Failed to create a user group with name '%1\$s' as a child of '%2\$s'", $name, $parent->getGroupName())); } else { throw new UserMessageException(t("Failed to create a user group with name '%s'", $name)); } } } return $result; }
Get a user group (create it if it does not exist). @param string $name the group name @param string|Group|null $parent the parent group @return \Group
entailment
protected function getLocaleGroup($parentName, $locale) { if (!($locale instanceof LocaleEntity)) { $l = $this->app->make(LocaleRepository::class)->findApproved($locale); if ($l === null) { throw new UserMessageException(t("The locale identifier '%s' is not valid", $locale)); } $locale = $l; } $localeID = $locale->getID(); if (!isset($this->localeGroups[$parentName])) { $this->localeGroups[$parentName] = []; } if (!isset($this->localeGroups[$parentName][$localeID])) { $this->localeGroups[$parentName][$localeID] = $this->getGroup($localeID, $parentName); } return $this->localeGroups[$parentName][$localeID]; }
Get a locale group given its parent group name. @param string $parentName @param LocaleEntity|string $locale
entailment
public function getGlobalAdministrators() { if ($this->globalAdministrators === null) { $this->globalAdministrators = $this->getGroup(self::GROUPNAME_GLOBAL_ADMINISTRATORS); } return $this->globalAdministrators; }
Get the global administrators group. @return \Group
entailment
public function decodeAspiringTranslatorsGroup(Group $group) { $result = null; $match = null; if (preg_match('/^\/' . preg_quote(self::GROUPNAME_ASPIRING_TRANSLATORS, '/') . '\/(.+)$/', $group->getGroupPath(), $match)) { $result = $this->app->make(LocaleRepository::class)->findApproved($match[1]); } return $result; }
Check if a group is an aspiring translators group. If so returns the associated locale entity. @param Group $group @return LocaleEntity|null
entailment
public function deleteLocaleGroups($localeID) { foreach ([ self::GROUPNAME_LOCALE_ADMINISTRATORS, self::GROUPNAME_TRANSLATORS, self::GROUPNAME_ASPIRING_TRANSLATORS, ] as $parentGroupName) { $path = "/$parentGroupName/$localeID"; $group = Group::getByPath($path); if ($group !== null) { $group->delete(); } } }
Delete the user groups associated to a locale ID. @param string $localeID
entailment
public function clear() { $i=0; if ($glob=@glob($this->f3->get('ASSETS.public_path').'*')) foreach ($glob as $file) if (preg_match('/.+?\.(js|css)/i',basename($file))) { $i++; @unlink($file); } return $i; }
reset the temporary public path @return integer
entailment
public function getAssets($group='head',$type=null) { $assets = array(); if (!isset($this->assets[$group])) return $assets; $types = array_keys($this->assets[$group]); foreach($types as $asset_type) { if ($type && $type!=$asset_type) continue; krsort($this->assets[$group][$asset_type]); foreach($this->assets[$group][$asset_type] as $prio_set) foreach($prio_set as $asset) { if ($asset['origin']=='inline') $assets[$asset_type][$asset['data']] = $asset; else $assets[$asset_type][$asset['path']] = $asset; } $assets[$asset_type] = array_values($assets[$asset_type]); } return $assets; }
get sorted, unique assets from group @param string $group which group to render @param string $type which type to render, or all @return array
entailment
public function renderGroup($assets) { $out = array(); if ($this->f3->get('ASSETS.trim_public_root')) { $basePath=$this->f3->fixslashes(realpath($this->f3->fixslashes( $_SERVER['DOCUMENT_ROOT'].$this->f3->get('BASE')))); $cDir=$this->f3->fixslashes(getcwd()); $trimPublicDir=str_replace($cDir,'',$basePath); } foreach($assets as $asset_type=>$collection) { if ($this->f3->exists('ASSETS.filter.'.$asset_type,$filters)) { if (is_string($filters)) $filters = $this->f3->split($filters); $flist=array_flip($filters); $filters = array_values(array_intersect_key(array_replace($flist, $this->filter), $flist)); $collection = $this->f3->relay($filters,array($collection)); } foreach($collection as $asset) { if (isset($asset['path'])) { $path = $asset['path']; $mtime = ($this->f3->get('ASSETS.timestamps') && $asset['origin']!='external' && is_file($path)) ? '?'.filemtime($path) : ''; $base = ($this->f3->get('ASSETS.prepend_base') && $asset['origin']!='external' && is_file($path)) ? $this->f3->get('BASE').'/': ''; if (isset($trimPublicDir) && $asset['origin']!='external') $path = substr($path,strlen($trimPublicDir)); $asset['path'] = $base.$path.$mtime; } $out[]=$this->f3->call($this->formatter[$asset_type],array($asset)); } } return "\n\t".implode("\n\t",$out)."\n"; }
render asset group @param array $assets @return string
entailment
public function combine($collection) { $public_path = $this->f3->get('ASSETS.combine.public_path'); if (empty($collection) || count($collection) <= 1) return $collection; $cfs=$this->f3->get('ASSETS.combine.slots'); $slots=array_fill_keys(array_keys($cfs),array()); $sn=array_flip($cfs); // sort to slots $exclude = $this->f3->get('ASSETS.combine.exclude'); foreach($collection as $i=>$asset) { $a_slot = isset($asset['slot']) ? $asset['slot'] : NULL; // auto-create slot if ($a_slot && !isset($sn[$a_slot])) { $i=50; while (isset($slots[$i])) $i++; $slots[$i]=array(); $sn[$a_slot]=$i; } // inline if ($asset['origin']=='inline') { $slots[$sn[$a_slot?:'inline']][] = $asset; continue; } // external if ($asset['origin']=='external') { $slots[$sn[$a_slot?:'external']][]=$asset; } // internal elseif (is_file($asset['path']) && ( (!isset($asset['exclude']) || !in_array('combine',$this->f3->split($asset['exclude']))) && (empty($exclude) || !preg_match('/'.$exclude.'/i',$asset['path']))) && (!isset($asset['media']) || in_array($asset['media'],array('all','screen')))) { $slots[$sn[$a_slot?:'internal']][] = $asset; } else // excluded internal $slots[$sn['excluded']][] = $asset; } // proceed slots ksort($slots); $out = array(); foreach ($slots as $slotID => $assets) { $internal=array(); $inline=array(); $hash_key=array(); // categorize per slot foreach ($assets as $asset) { if ($slotID == $sn['excluded']) { $out[] = $asset; continue; } if ($asset['origin']=='internal') { $internal[$asset['type']][] = $asset; // check if one of our combined files was changed (mtime) if (!isset($hash_key[$asset['type']])) $hash_key[$asset['type']]=''; $hash_key[$asset['type']].=$asset['path'].filemtime($asset['path']); } elseif ($asset['origin']=='external') $out[] = $asset; elseif ($asset['origin']=='inline') $inline[$asset['type']][] = $asset['data']; } // combine internals to one file if (!empty($internal)) { foreach ($internal as $type => $int_a) { $filepath = $public_path.$this->f3->hash($hash_key[$type]).'.'.$type; if (!is_dir($public_path)) mkdir($public_path,0777,true); $content = array(); if (!is_file($filepath)) { foreach($int_a as $asset) { $data = $this->f3->read($asset['path']); if ($type=='css') $data = $this->fixRelativePaths($data, pathinfo($asset['path'],PATHINFO_DIRNAME).'/',$public_path); $content[] = $data; } $this->f3->write($filepath, implode(($type=='js'?';':'')."\n",$content)); } $extra_attr=[]; if ($this->f3->get('ASSETS.combine.merge_attributes')) foreach($int_a as $asset) $extra_attr+=array_diff_key($asset, array_flip([ 'path','origin','type','exclude' ])); $out[] = array( 'path'=>$filepath, 'type'=>$type, 'origin'=>'internal' )+$extra_attr; } } // combine inline if (!empty($inline)) { foreach ($inline as $type => $inl_a) { $out[] = array( 'data'=>implode($inl_a), 'type'=>$type, 'origin'=>'inline' ); } } } return $out; }
combine a whole asset group @param $collection @return array
entailment
public function minify($collection) { // check final path $public_path = $this->f3->get('ASSETS.minify.public_path'); if (!is_dir($public_path)) mkdir($public_path,0777,true); $type = false; $inline_stack = array(); foreach($collection as $i=>&$asset) { $type = $asset['type']; if ($asset['origin']=='inline') { $slot = $asset['slot'] ?: 'default'; $inline_stack[$slot][] = $asset['data']; unset($collection[$i]); unset($asset); continue; } $path = $asset['path']; $exclude = $this->f3->get('ASSETS.minify.exclude'); // skip external files if ($asset['origin'] == 'external') continue; elseif (is_file($path) && ( (!isset($asset['exclude']) || !in_array('minify',$this->f3->split($asset['exclude']))) && (empty($exclude) || !preg_match('/'.$exclude.'/i',$path)))) { // proceed $path_parts = pathinfo($path); $filename = $path_parts['filename'].'.' .substr($this->f3->hash($path),0,5).'.min.'.$type; if (!is_file($public_path.$filename) || (filemtime($path)>filemtime($public_path.$filename))) { $min = $this->f3->call($this->f3->get('ASSETS.minify.compiler.'.$type), [$path_parts['basename'],$path_parts['dirname'].'/']); if ($type=='css') $min = $this->fixRelativePaths($min, $path_parts['dirname'].'/',$public_path); $this->f3->write($public_path.$filename,$min); } $asset['path'] = $public_path.$filename; } unset($asset); } if (!empty($inline_stack)) { foreach ($inline_stack as $slotGroup=>$inlineData) { $data = implode($inlineData); if ($this->f3->get('ASSETS.minify.inline')) { // this is probably pretty slow $hash = $this->f3->hash($data); $filename = $hash.'.min.'.$type; if (!is_file($public_path.$filename)) { $this->f3->write($public_path.$filename,$data); $min = \Web::instance()->minify($filename,null,false, $public_path); $this->f3->write($public_path.$filename,$min); } $collection[] = array( 'path'=>$public_path.$filename, 'type'=>$type, 'origin'=>'internal', 'slot'=>$slotGroup, ); } else { $collection[] = array( 'data'=>$data, 'type'=>$type, 'origin'=>'inline', 'slot'=>$slotGroup, ); } } } return $collection; }
minify each file in a collection @param $collection @return mixed
entailment
public function fixRelativePaths($content,$path,$targetDir=null) { // Rewrite relative URLs in CSS $f3=$this->f3; $method=$f3->get('ASSETS.fixRelativePaths'); if ($method!==FALSE) { $webBase=$f3->get('BASE'); // fix base path (resolve symbolic links) $basePath=$f3->fixslashes(realpath( $f3->fixslashes($_SERVER['DOCUMENT_ROOT'].$webBase)).DIRECTORY_SEPARATOR); // parse content for URLs $content=preg_replace_callback( '/\b(?<=url)\((?:([\"\']?)(.+?)((\?.*?)?)\1)\)/s', function($url) use ($path,$f3,$webBase,$basePath,$targetDir,$method) { // Ignore absolute URLs if (preg_match('/https?:/',$url[2]) || !$rPath=realpath($path.$url[2])) return $url[0]; if ($method=='relative') { // relative from new public file path $filePathFromBase=str_replace($basePath,'',$f3->fixslashes($rPath)); $rel=$this->relPath($targetDir,$filePathFromBase); return '('.$url[1].$rel.(isset($url[4])?$url[4]:'').$url[1].')'; } elseif ($method=='absolute') { // absolute to web root / base return '('.$url[1].preg_replace( '/'.preg_quote($basePath,'/').'(.+)/', '\1',$webBase.'/'.$f3->fixslashes($rPath).(isset($url[4])?$url[4]:'') ).$url[1].')'; } return $url[0]; },$content); } return $content; }
Rewrite relative URLs in CSS @author Bong Cosca, from F3 v2.0.13, http://bit.ly/1Mwl7nq @param string $content @param string $path @param string $targetDir @return string
entailment
public function relPath($from,$to) { $expFrom = explode('/',$from); $expTo = explode('/',$to); $max=max(count($expFrom),count($expTo)); $rel = []; $base=TRUE; for ($i=0;$i<$max;$i++) { if ($base && isset($expTo[$i]) && isset($expFrom[$i]) && $expTo[$i] === $expFrom[$i]) continue; else $base=FALSE; if (!empty($expFrom[$i])) array_unshift($rel,'..'); if (!empty($expTo[$i])) array_push($rel,$expTo[$i]); } return implode('/',$rel); }
assemble relative path to go from A to B @param $from @param $to @return string
entailment
public function add($path,$type,$group='head',$priority=5,$slot=null,$params=null) { if (!isset($this->assets[$group])) $this->assets[$group]=array(); if (!isset($this->assets[$group][$type])) $this->assets[$group][$type]=array(); $asset = array( 'path'=>$path, 'type'=>$type, 'slot'=>$slot ) + ($params?:array()); if (preg_match('/^(http(s)?:)?\/\/.*/i',$path)) { $asset['origin'] = 'external'; $this->assets[$group][$type][$priority][]=$asset; return; } foreach ($this->f3->split($this->f3->get('UI')) as $dir) if (is_file($view=$this->f3->fixslashes($dir.$path))) { $asset['path']=ltrim($view,'./'); $asset['origin']='internal'; $this->assets[$group][$type][$priority][]=$asset; return; } // file not found if ($handler=$this->f3->get('ASSETS.onFileNotFound')) $this->f3->call($handler,array($path,$this)); // mark unknown file as external $asset['origin'] = 'external'; $this->assets[$group][$type][$priority][]=$asset; }
add an asset @param string $path @param string $type @param string $group @param int $priority @param string $slot @param array $params
entailment
public function addJs($path,$priority=5,$group='footer',$slot=null) { $this->add($path,'js',$group,$priority,$slot); }
add a javascript asset @param string $path @param int $priority @param string $group @param null $slot
entailment
public function addCss($path,$priority=5,$group='head',$slot=null) { $this->add($path,'css',$group,$priority,$slot); }
add a css asset @param string $path @param int $priority @param string $group @param null $slot
entailment
public function addInline($content,$type,$group='head',$slot='inline') { if (!isset($this->assets[$group])) $this->assets[$group]=array(); if (!isset($this->assets[$group][$type])) $this->assets[$group][$type]=array(); $this->assets[$group][$type][3][]=array( 'data'=>$content, 'type'=>$type, 'origin'=>'inline', 'slot'=>$slot, ); }
add inline script or styles @param string $content @param string $type @param string $group @param string $slot
entailment
public function addNode($node) { $src=false; // find src if (array_key_exists('src',$node)) $src = $node['src']; elseif (array_key_exists('href',$node)) $src = $node['href']; if ($src) { // find type if (!isset($node['type'])) { if (preg_match('/.*\.(css|js)(?=[?#].*|$)/i',$src,$match)) $node['type'] = $match[1]; elseif (array_key_exists('src',$node)) $node['type'] = 'js'; elseif (array_key_exists('href',$node)) $node['type'] = 'css'; elseif(empty($type)) // unknown file type return ""; } $type = $node['type']; // default slot is based on the type if (!isset($node['group'])) $node['group'] = ($node['type'] == 'js') ? 'footer' : 'head'; if (!isset($node['priority'])) $node['priority'] = 5; if (!isset($node['slot'])) $node['slot'] = null; $group = $node['group']; $prio = $node['priority']; $slot = $node['slot']; unset($node['priority'],$node['src'],$node['href'], $node['group'],$node['type'],$node['slot']); $this->add($src,$type,$group,$prio,$slot,$node); } }
push new asset during template execution @param $node @return string
entailment
function parseNode($node) { $src=false; $params = array(); if (isset($node['@attrib'])) { $params = $node['@attrib']; unset($node['@attrib']); } // find src if (array_key_exists('src',$params)) $src = $params['src']; elseif (array_key_exists('href',$params)) $src = $params['href']; if ($src) { $out = '<?php \Assets::instance()->addNode(array('; foreach($params as $key=>$val) $out.=var_export($key,true).'=>'.(preg_match('/{{(.+?)}}/s',$val) ?$this->template->token($val):var_export($val,true)).','; $out.=')); ?>'; return $out; } // inner content if (isset($node[0]) && isset($params['type'])) { if (!isset($params['group'])) $params['group'] = ($params['type'] == 'js') ? 'footer' : 'head'; if (!isset($params['slot'])) $params['slot'] = 'inline'; if ($this->f3->get('ASSETS.handle_inline')) return '<?php \Assets::instance()->addInline('. '$this->resolve('.(var_export($node,true)). ',get_defined_vars(),0,false,false),'. var_export($params['type'],true).','. var_export($params['group'],true).','. var_export($params['slot'],true).'); ?>'; else // just bypass return $this->f3->call($this->formatter[$params['type']],array(array( 'data'=>$this->template->build($node), 'origin'=>'inline' ))); } }
parse node data on template compiling @param $node @return string
entailment
function resolveAttr(array $attr) { $out = ''; foreach ($attr as $key => $value) { // build dynamic tokens if (preg_match('/{{(.+?)}}/s', $value)) $value = $this->template->build($value); if (preg_match('/{{(.+?)}}/s', $key)) $key = $this->template->build($key); // inline token if (is_numeric($key)) $out .= ' '.$value; // value-less parameter elseif($value==NULL) $out .= ' '.$key; // key-value parameter else $out .= ' '.$key.'="'.$value.'"'; } return $out; }
general bypass for unhandled tag attributes @param array $attr @return string
entailment
static public function renderLinkCSSTag(array $node) { if (isset($node['@attrib'])) // detect stylesheet link tags if ((isset($node['@attrib']['type']) && $node['@attrib']['type'] == 'text/css') || (isset($node['@attrib']['rel']) && $node['@attrib']['rel'] == 'stylesheet')) { $node['@attrib']['type']='css'; return static::renderAssetTag($node); } else { // skip other other <link> nodes and render them directly $as=\Assets::instance(); $params = ''; if (isset($node['@attrib'])) { $params = $as->resolveAttr($node['@attrib']); unset($node['@attrib']); } return "\t".'<link'.$params.' />'; } }
crawl <link> tags in greedy mode @param array $node @return mixed|string
entailment
public function _head($node) { unset($node['@attrib']); $content = array(); // bypass inner content nodes foreach ($node as $el) $content[] = $this->template->build($el); return '<head>'.implode("\n", $content). $this->render('head')."\n".'</head>'; }
auto-append slot marker into <head> @param $node @return string
entailment
public function _body($node) { $params = ''; if (isset($node['@attrib'])) { $params = $this->resolveAttr($node['@attrib']); unset($node['@attrib']); } $content = array(); // bypass inner content nodes foreach ($node as $el) $content[] = $this->template->build($el); return '<body'.$params.'>'.implode("\n", $content)."\n". $this->render('footer')."\n".'</body>'; }
auto-append footer slot marker into <body> @param $node @return string
entailment
public function map() { Route::namespace($this->namespace)->group(function (Router $router) { /* * Front office routes */ if ($page = TypiCMS::getPageLinkedToModule('news')) { $router->middleware('public')->group(function (Router $router) use ($page) { $options = $page->private ? ['middleware' => 'auth'] : []; foreach (locales() as $lang) { if ($page->translate('status', $lang) && $uri = $page->uri($lang)) { $router->get($uri, $options + ['uses' => 'PublicController@index'])->name($lang.'::index-news'); $router->get($uri.'.xml', $options + ['uses' => 'PublicController@feed'])->name($lang.'::news-feed'); $router->get($uri.'/{slug}', $options + ['uses' => 'PublicController@show'])->name($lang.'::news'); } } }); } /* * Admin routes */ $router->middleware('admin')->prefix('admin')->group(function (Router $router) { $router->get('news', 'AdminController@index')->name('admin::index-news')->middleware('can:see-all-news'); $router->get('news/create', 'AdminController@create')->name('admin::create-news')->middleware('can:create-news'); $router->get('news/{news}/edit', 'AdminController@edit')->name('admin::edit-news')->middleware('can:update-news'); $router->post('news', 'AdminController@store')->name('admin::store-news')->middleware('can:create-news'); $router->put('news/{news}', 'AdminController@update')->name('admin::update-news')->middleware('can:update-news'); }); /* * API routes */ $router->middleware('api')->prefix('api')->group(function (Router $router) { $router->middleware('auth:api')->group(function (Router $router) { $router->get('news', 'ApiController@index')->middleware('can:see-all-news'); $router->patch('news/{news}', 'ApiController@updatePartial')->middleware('can:update-news'); $router->delete('news/{news}', 'ApiController@destroy')->middleware('can:delete-news'); $router->get('news/{news}/files', 'ApiController@files')->middleware('can:update-news'); $router->post('news/{news}/files', 'ApiController@attachFiles')->middleware('can:update-news'); $router->delete('news/{news}/files/{file}', 'ApiController@detachFile')->middleware('can:update-news'); }); }); }); }
Define the routes for the application. @return null
entailment
public function actionCreate() { $stdout = ''; foreach ($this->db->schema->getTableSchemas() as $table) { if ($table->name === $this->migrationTable) { continue; } $stdout .= static::generateCreateTable($table->name). static::generateColumns($table->columns, $this->db->schema->findUniqueIndexes($table)). static::generatePrimaryKey($table->primaryKey, $table->columns). static::generateTableOptions(); } foreach ($this->db->schema->getTableSchemas() as $table) { $stdout .= $this->generateForeignKey($table); } $this->stdout($stdout); }
Generates the 'createTable' code. @return integer the status of the action execution
entailment
public function actionDrop() { $stdout = ''; foreach ($this->db->schema->getTableSchemas() as $table) { if ($table->name === $this->migrationTable) { continue; } $stdout .= static::generateDropTable($table->name); if (!empty($table->foreignKeys)) { $stdout .= ' // fk: '; foreach ($table->foreignKeys as $fk) { foreach ($fk as $k => $v) { if (0 === $k) { continue; } $stdout .= "$k, "; } } $stdout = rtrim($stdout, ', '); } $stdout .= "\n"; } $this->stdout($stdout); }
Generates the 'dropTable' code. @return integer the status of the action execution
entailment
private static function generateColumns(array $columns, array $unique) { $definition = ''; foreach ($columns as $column) { $tmp = sprintf(" '%s' => \$this->%s%s,\n", $column->name, static::getSchemaType($column), static::other($column, $unique)); if (null !== $column->enumValues) { $tmp = static::replaceEnumColumn($tmp); } $definition .= $tmp; } return $definition; }
Returns the columns definition. @param array $columns @param array $unique unique indexes @return string
entailment
private static function generatePrimaryKey(array $pk, array $columns) { if (empty($pk)) { return ''; } // Composite primary keys if (2 <= count($pk)) { $compositePk = implode(', ', $pk); return " 'PRIMARY KEY ($compositePk)',\n"; } // Primary key not an auto-increment $flag = false; foreach ($columns as $column) { if ($column->autoIncrement) { $flag = true; } } if (false === $flag) { return sprintf(" 'PRIMARY KEY (%s)',\n", $pk[0]); } return ''; }
Returns the primary key definition. @param array $pk @param array $columns @return string the primary key definition
entailment
private function generateForeignKey($table) { if (empty($table->foreignKeys)) { return; } $definition = "// fk: $table->name\n"; foreach ($table->foreignKeys as $fk) { $refTable = ''; $refColumns = ''; $columns = ''; foreach ($fk as $k => $v) { if (0 === $k) { $refTable = $v; } else { $columns = $k; $refColumns = $v; } } $definition .= sprintf("\$this->addForeignKey('%s', '{{%%%s}}', '%s', '{{%%%s}}', '%s');\n", 'fk_'.$table->name.'_'.$columns, $table->name, $columns, $refTable, $refColumns); } return "$definition\n"; }
Returns the foreign key definition. @param TableSchema[] $table @return string|null foreign key definition or null
entailment
private static function getSchemaType($column) { // primary key if ($column->isPrimaryKey && $column->autoIncrement) { if ('bigint' === $column->type) { return 'bigPrimaryKey()'; } return 'primaryKey()'; } // boolean if ('tinyint(1)' === $column->dbType) { return 'boolean()'; } // smallint if ('smallint' === $column->type) { if (null === $column->size) { return 'smallInteger()'; } return 'smallInteger'; } // bigint if ('bigint' === $column->type) { if (null === $column->size) { return 'bigInteger()'; } return 'bigInteger'; } // enum if (null !== $column->enumValues) { // https://github.com/yiisoft/yii2/issues/9797 $enumValues = array_map('addslashes', $column->enumValues); return "enum(['".implode('\', \'', $enumValues)."'])"; } // others if (null === $column->size && 0 >= $column->scale) { return $column->type.'()'; } return $column->type; }
Returns the schema type. @param ColumnSchema[] $column @return string the schema type
entailment
private static function other($column, array $unique) { $definition = ''; // size if (null !== $column->scale && 0 < $column->scale) { $definition .= "($column->precision,$column->scale)"; } elseif (null !== $column->size && !$column->autoIncrement && 'tinyint(1)' !== $column->dbType) { $definition .= "($column->size)"; } elseif (null !== $column->size && !$column->isPrimaryKey && $column->unsigned) { $definition .= "($column->size)"; } // unsigned if ($column->unsigned) { $definition .= '->unsigned()'; } // null if ($column->allowNull) { $definition .= '->null()'; } elseif (!$column->autoIncrement) { $definition .= '->notNull()'; } // unique key if (!$column->isPrimaryKey && !empty($unique)) { foreach ($unique as $name) { if (reset($name) === $column->name) { $definition .= '->unique()'; } } } // default value if ($column->defaultValue instanceof Expression) { $definition .= "->defaultExpression('$column->defaultValue')"; } elseif (is_int($column->defaultValue)) { $definition .= "->defaultValue($column->defaultValue)"; } elseif (is_bool($column->defaultValue)) { $definition .= '->defaultValue('.var_export($column->defaultValue, true).')'; } elseif (is_string($column->defaultValue)) { $definition .= "->defaultValue('".addslashes($column->defaultValue)."')"; } // comment if (null !== $column->comment && '' !== $column->comment) { $definition .= "->comment('".addslashes($column->comment)."')"; } // append return $definition; }
Returns the other definition. @param ColumnSchema[] $column @param array $unique @return string the other definition
entailment
private function byOption() { $option = new OptionForCli($this->interactor); $option->setOption($this->option); $option->execute(); }
Download by option. @return void
entailment
public function getModelRepository($config = null, $data = null) { return new Repository\ModelRepository($this->getRequest(), $config, $data); }
@param array|null $config @param array|null $data @return Repository\ModelRepository
entailment
public function getInputRepository($config = null, $data = null) { return new Repository\InputRepository($this->getRequest(), $config, $data); }
@param $config @param $data @return Repository\InputRepository
entailment
public function getSearchInputRepository($config = null, $data = null) { return new Repository\SearchInputRepository($this->getRequest(), $config, $data); }
@param $config @param $data @return Repository\SearchInputRepository
entailment
public function getSearchModelRepository($config = null, $data = null) { return new Repository\SearchModelRepository($this->getRequest(), $config, $data); }
@param $config @param $data @return Repository\SearchModelRepository
entailment
protected function write(array $record) { $url = sprintf( 'https://api.telegram.org/bot%s/sendMessage', $this->botToken ); $data = [ 'chat_id' => $this->chatID, 'disable_web_page_preview' => true, 'parse_mode' => 'HTML', ]; $this->buildMessageText($data, $record['channel'], $record['message'] . $record['message'] . $record['message']); $ch = curl_init($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', ]); Util::execute($ch); }
{@inheritdoc}
entailment
public function add($input_data) { $data['inputs'] = []; if (is_array($input_data)) { foreach ($input_data as $image) { $data['inputs'][] = $this->addNewImage($image); } } else { $data['inputs'][] = $this->addNewImage($input_data); } $inputResult = $this->getRequest()->request( 'POST', $this->getRequestUrl('inputs'), $data ); return $this->getInputsFromResult($inputResult); }
Add Input Method @param $input_data @return array @throws \Exception
entailment
public function addNewImage(Input $image) { $data = []; $data['data'] = [ 'image' => $this->generateImageAddress($image->getImage(), $image->getImageMethod()), ]; if ($image->getId()) { $data = $this->addImageId($data, $image->getId()); } if ($image->getCrop()) { $data['data']['image'] = $this->addImageCrop($data['data']['image'], $image->getCrop()); } if ($image->getConcepts()) { $data['data'] = $this->addImageConcepts($data['data'], $image->getConcepts()); } if ($image->getMetaData()) { $data['data'] = $this->addImageMetadata($data['data'], $image->getMetaData()); } return $data; }
Adds new Image to Custom Input @param Input $image @return array
entailment
public function generateImageAddress(string $image, $method = null) { if ($method == Input::IMG_BASE64) { return ['base64' => $image]; } elseif ($method == Input::IMG_PATH) { if (!file_exists($image)) { throw new FileNotFoundException($image); } return ['base64' => base64_encode(file_get_contents($image))]; } else { return ['url' => $image]; } }
Generate Image With Download Type @param $image @param null $method @return array
entailment
public function addImageConcepts(array $data, array $concepts) { $data['concepts'] = []; foreach ($concepts as $concept) { $data['concepts'][] = [ 'id' => $concept->getId(), 'value' => $concept->getValue(), ]; } return $data; }
Adds Image Concepts to Image Data @param array $data @param array $concepts @return array
entailment
public function addImageMetadata(array $data, array $metadata) { $data['metadata'] = []; foreach ($metadata as $meta_name => $meta_value) { $data['metadata'][$meta_name] = $meta_value; } return $data; }
Adds Image Metadaya to Image Data @param array $data @param array $metadata @return array
entailment
public function get() { $inputResult = $this->getRequest()->request( 'GET', $this->getRequestUrl('inputs') ); return $this->getInputsFromResult($inputResult); }
Gets All Inputs @return array @throws \Exception
entailment
public function getById($id) { $inputResult = $this->getRequest()->request( 'GET', $this->getRequestUrl(sprintf('inputs/%s', $id)) ); if (isset($inputResult['input'])) { $input = new Input($inputResult['input']); } else { throw new \Exception('Input Not Found'); } return $input; }
Gets Input By Id @param $id @return Input @throws \Exception
entailment
public function getStatus() { $statusResult = $this->getRequest()->request( 'GET', $this->getRequestUrl('inputs/status') ); if (isset($statusResult['counts'])) { $status = $statusResult['counts']; } else { throw new \Exception('Status Not Found'); } return $status; }
Gets Status of your Inputs @return array @throws \Exception
entailment
public function deleteById($id) { $deleteResult = $this->getRequest()->request( 'DELETE', $this->getRequestUrl(sprintf('inputs/%s', $id)) ); return $deleteResult['status']; }
Deletes Input By Id @param $id @return array
entailment
public function deleteByIdArray(array $ids) { $data['ids'] = $ids; $deleteResult = $this->getRequest()->request( 'DELETE', $this->getRequestUrl('inputs'), $data ); return $deleteResult['status']; }
Deletes Inputs By Id Array @param array $ids @return array
entailment
public function updateInputConcepts(array $conceptsArray, $action) { $data['inputs'] = []; foreach ($conceptsArray as $inputId => $inputConcepts) { $input = []; $input['id'] = (string)$inputId; $input['data'] = []; $input['data'] = $this->addImageConcepts($input['data'], $inputConcepts); $data['inputs'][] = $input; } $data['action'] = $action; $updateResult = $this->getRequest()->request( 'PATCH', $this->getRequestUrl('inputs'), $data ); return $this->getInputsFromResult($updateResult); }
Common Input's Concepts Update Method @param array $conceptsArray @param $action @return array
entailment
public function load() { if (empty($this->storage)) { throw new Exception('Empty config storage'); } $storage = $this->getStorage(); $storage->load(); return $this->fromArray($storage->get()); }
Loads config from storage @return $this @throws \Runn\Core\Exception
entailment
public function handleRequest(RequestInterface $request, callable $next, callable $first) { $request = $this->authentication->authenticate($request); return $next($request); }
{@inheritdoc}
entailment
protected function checkRequired() { $errors = new Exceptions(); foreach ($this->getRequiredKeys() as $required) { if (!isset($this->$required)) { $errors->add(new Exception('Required property "' . $required . '" is missing')); } } if (!$errors->empty()) { throw $errors; } return true; }
Checks if all required properties are set @return bool @throws \Runn\Core\Exceptions
entailment
private function getNotificationCategory(NotificationEntity $notification) { $fqnClass = $notification->getFQNClass(); if (!isset($this->categories[$fqnClass])) { if (!class_exists($fqnClass, true)) { $this->categories[$fqnClass] = sprintf('Unable to find the category class %s', $fqnClass); } else { $obj = null; $error = null; try { $obj = $this->app->make($fqnClass); } catch (Exception $x) { $error = $x; } catch (Throwable $x) { $error = $x; } if ($error !== null) { $this->categories[$fqnClass] = sprintf('Failed to initialize category class %1$s: %2$s', $fqnClass, $error->getMessage()); } elseif (!($obj instanceof CategoryInterface)) { $this->categories[$fqnClass] = sprintf('The class %1$s does not implement %2$s', $fqnClass, CategoryInterface::class); } else { $this->categories[$fqnClass] = $obj; } } } if (is_string($this->categories[$fqnClass])) { throw new Exception($this->categories[$fqnClass]); } return $this->categories[$fqnClass]; }
@param string $fqnClass @throws Exception @return CategoryInterface
entailment
public function createHelpMessage() { $m = 'Usage:' . PHP_EOL; $m .= ' -h,--help' . PHP_EOL; $m .= ' Display help message and exit.' . PHP_EOL; $m .= ' -p platform (required)' . PHP_EOL; $m .= ' Select platform [m]ac or [w]indows or [l]inux.' . PHP_EOL; $m .= ' Required except that "--help, -h" is specified.' . PHP_EOL; $m .= ' -d output_dir_path' . PHP_EOL; $m .= ' Enter the output directory path.' . PHP_EOL; $m .= ' If not specified, it is output to the path specified by .env.dafault|.env(DEFAULT_OUTPUT_DIR).' . PHP_EOL; $m .= ' If there is still no value, it is output to "selenium-downloader/xxx".' . PHP_EOL; $m .= ' -s selenium-standalone-server_ver' . PHP_EOL; $m .= ' Enter the version of selenium-standalone-server. (e.g 3.8.1, 3.7(3.7.0)' . PHP_EOL; $m .= ' (Recommend version 3.8.1)' . PHP_EOL; $m .= ' -c ChromeDriver_ver' . PHP_EOL; $m .= ' Enter the version of ChromeDriver. (e.g 2.43' . PHP_EOL; $m .= ' -g geckodriver_ver' . PHP_EOL; $m .= ' Enter the version of GeckoDriver. (e.g 0.23(0.23.0), 0.20.1' . PHP_EOL; $m .= ' -i IEDriverServer_ver' . PHP_EOL; $m .= ' Enter the version of IEDriverServer. (e.g 3.14(3.14.0)' . PHP_EOL; $m .= ' -b bit_of_os' . PHP_EOL; $m .= ' Enter the number of OS bits (32 or 64).' . PHP_EOL; $m .= ' Default is "32" (Because key input is earlier than 64bit version).' . PHP_EOL; $m .= ' Valid only when IEDriverServer is specified.' . PHP_EOL; $m .= PHP_EOL; $m .= 'e.g) 1 Basic.' . PHP_EOL; $m .= '$ php selenium_downloader.php -p m -s 3.8.1 -c 2.43 -g 0.23' . PHP_EOL; $m .= 'e.g) 2 When specifying the output directory.' . PHP_EOL; $m .= '$ php selenium_downloader.php -p m -d /your/path/to -s 3.8.1' . PHP_EOL; $m .= 'e.g) 3 When downloading the 64 bit version of the IEDriverServer.' . PHP_EOL; $m .= '$ php selenium_downloader.php -p w -i 3.14.0 -b 64' . PHP_EOL; $m .= 'e.g) 4 When downloading only geckodriver.' . PHP_EOL; $m .= '$ php selenium_downloader.php -p m -g 0.23' . PHP_EOL; $m .= 'or' . PHP_EOL; $m .= '$ php selenium_downloader.php -p m -s "" -c "" -g 0.23' . PHP_EOL; return $m; }
Create help message. @return string
entailment
private function _getopt() { $shortopts = OptionConfig::HELP; // help $shortopts .= OptionConfig::PLATFORM . ':'; // platform $shortopts .= OptionConfig::OUTPUT_DIR . ':'; // output dir. $shortopts .= OptionConfig::SELENIUM_VER . ':'; // Selenium-Standalone-Server Ver. $shortopts .= OptionConfig::CHROME_DRIVER_VER . ':'; // ChromeDriver Ver. $shortopts .= OptionConfig::GECKO_DRIVER_VER . ':'; // GeckoDriver Ver. $shortopts .= OptionConfig::IE_DRIVER_VER . ':'; // IEDriverServer Ver. $shortopts .= OptionConfig::OS_BIT_VER . ':'; // bit of OS (Default 32). $longopts = array( OptionConfig::HELP_LONG . '::', // help ); return getopt($shortopts, $longopts); }
Acquire command line option. @return array
entailment
public function getRegisteredParsers() { if ($this->parserInstances === null) { $result = []; foreach ($this->parsers as $parser) { if ($parser instanceof ParserInterface) { $result[] = $parser; } else { $instance = $this->app->make($parser); if (!($instance instanceof ParserInterface)) { throw new UserMessageException(t(/*i18n: %1$s is the name of a PHP class, %2$s is the name of a PHP interface*/'%1$s does not implement %2$s', $parser, ParserInterface::class)); } $result[] = $instance; } } $this->parserInstances = $result; } else { $result = $this->parserInstances; } return $result; }
Get the list of registered parsers. @throws UserMessageException @return ParserInterface[]
entailment
public function showShareButtons( Twig_Environment $twigEnvironment, array $options = array(), array $providers = array() ) { $this->shareButtonsRenderer->setTemplateEngine($twigEnvironment); if (isset($providers)) { $options['providers'] = $providers; } if (!isset($options['template'])) { $options['template'] = $this->configResolver->getParameter('template', 'ez_share_buttons'); } return $twigEnvironment->render(sprintf( 'EzSystemsShareButtonsBundle::%s.html.twig', $options['template'] ), array( 'shareButtons' => $this->shareButtonsRenderer->render($options), )); }
Renders share buttons bar template based on user settings. @param \Twig_Environment $twigEnvironment @param array $options @param string[] $providers @return string
entailment
public static function getFile($tmp = true, $name = null) { return ($tmp ? realpath(sys_get_temp_dir()) : '').'/'.(null === $name ? uniqid() : $name); }
Gets the file. @param bool $tmp TRUE if the file should be in the "/tmp" directory else FALSE. @param string|null $name The name. @return string The file.
entailment
public function run(InputInterface $input = null, OutputInterface $output = null) { if (null === $input) { // rewrite the input for single command usage $argv = $_SERVER['argv']; $scriptName = array_shift($argv); array_unshift($argv, 'lint'); array_unshift($argv, $scriptName); $input = new ArgvInput($argv); } return parent::run($input, $output); }
{@inheritdoc} @SuppressWarnings(PHPMD.Superglobals)
entailment
protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output) { if ('version' != $command->getName()) { $output->writeln($this->getLongVersion()); } return parent::doRunCommand($command, $input, $output); }
{@inheritdoc}
entailment
protected function before() { if ($this->option->isSpecifiedHelp()) { $this->interactor->out($this->option->createHelpMessage()); $this->interactor->quit(); } if ($this->getPlatform() === '') { $this->interactor->out('Please input platform(-' . OptionConfig::PLATFORM .' [m]ac or [w]indows or [l]inux).'); $this->interactor->quit(); } if ($this->getOutputDir() === '') { $this->interactor->out('Please input an existing writable directory path(-' . OptionConfig::OUTPUT_DIR . ').'); $this->interactor->quit(); } }
{@inheritdoc}
entailment
public function setAuthorizationFlow($name, $flow, $authorizationUrl, $tokenUrl, $refreshUrl = null, array $scopes = null) { if (!isset($this->authFlows[$name])) { $this->authFlows[$name] = []; } $this->authFlows[$name][] = [$flow, $authorizationUrl, $tokenUrl, $refreshUrl, $scopes]; }
Configuration details for a supported OAuth Flow @param string $name @param integer $flow @param string $authorizationUrl @param string $tokenUrl @param string|null $refreshUrl @param array|null $scopes
entailment
private function getGitRepositories(array $filter) { $allGitRepositories = $this->app->make(GitRepositoryRepository::class)->findAll(); if (empty($allGitRepositories)) { throw new Exception('No git repository defined'); } if (count($filter) === 0) { $result = $allGitRepositories; } else { $result = []; foreach ($filter as $f) { $found = null; foreach ($allGitRepositories as $r) { if (strcasecmp($r->getName(), $f) === 0) { if ($found !== null) { throw new Exception("Duplicated repository specified: $f"); } else { $found = $r; } } } if ($found === null) { throw new Exception("Unable to find a repository with name $f"); } $result[] = $found; } } return $result; }
@param string[] $filter @throws Exception @return \CommunityTranslation\Entity\GitRepository[]
entailment
public static function pack($data, $returnJsonEncode = false) { self::resetSchema(); if (!$returnJsonEncode) { return self::encode($data); } return json_encode(self::encode($data)); }
Method RJson::pack($data), return compact array @param $data @param bool $returnJsonEncode @return array|bool|string
entailment
public static function unpack($data, $isJson = false) { self::resetSchema(); if ( $isJson ) { $data = json_decode($data); } return self::decode($data); }
RJson Unpack Example of use RJson::unpack($data); @param $data @param bool $isJson @return array|bool|string
entailment
private static function decode($data) { if((is_array($data) && isset($data[0])) || (isset($data[0]) && !is_string($data[0]))) { return self::parseArray($data); } else if (is_null($data) || is_scalar($data)) { return $data; } else { return self::decodeNewObject($data); } }
Decode Array collection @param $data @return array|bool
entailment
protected function getVolatileDirectory() { if ($this->volatileDirectory === null) { $this->volatileDirectory = $this->app->make(VolatileDirectory::class); } return $this->volatileDirectory; }
Get the volatile instance that contains the decompressed contents of the package archive. @return VolatileDirectory
entailment
public function extract() { if ($this->extractedWorkDir !== null) { return; } if (!is_file($this->packageArchive)) { throw new UserMessageException(t('Archive not found: %s', $this->packageArchive)); } try { $workDir = $this->getVolatileDirectory()->getPath(); try { $this->app->make('helper/zip')->unzip($this->packageArchive, $workDir); } catch (\Exception $x) { throw new UserMessageException($x->getMessage()); } $fs = $this->getVolatileDirectory()->getFilesystem(); $dirs = array_filter($fs->directories($workDir), function ($dn) { return strpos(basename($dn), '.') !== 0; }); if (count($dirs) === 1) { $someFile = false; foreach ($fs->files($workDir) as $fn) { if (strpos(basename($fn), '.') !== 0) { $someFile = true; break; } } if ($someFile === false) { $workDir = $dirs[0]; } } } catch (\Exception $x) { $this->volatileDirectory = null; throw $x; } $this->extractedWorkDir = $workDir; }
Extract the archive (if not already done). @throws UserMessageException
entailment
public function repack() { $this->extract(); try { $this->app->make('helper/zip')->zip($this->getVolatileDirectory()->getPath(), $this->packageArchive, ['includeDotFiles' => true]); } catch (\Exception $x) { throw new UserMessageException($x->getMessage()); } }
Re-create the source archive with the contents of the extracted directory. @throws UserMessageException
entailment
public static function create($fqnClass, array $notificationData = [], $priority = null) { if (!is_numeric($priority)) { $priority = 0; if (class_exists($fqnClass) && class_exists(ReflectionClass::class)) { $reflectionClass = new ReflectionClass($fqnClass); $classConstants = $reflectionClass->getConstants(); if (isset($classConstants['PRIORITY'])) { $priority = (int) $classConstants['PRIORITY']; } } } $result = new static(); $result->createdOn = new DateTime(); $result->updatedOn = new DateTime(); $result->fqnClass = (string) $fqnClass; $result->priority = (int) $priority; $result->notificationData = $notificationData; $result->deliveryAttempts = 0; $result->sentOn = null; $result->sentCountPotential = null; $result->sentCountActual = null; $result->deliveryErrors = []; return $result; }
Create a new (unsaved) instance. @param string $fqnClass The fully qualified name of the category class @param array $notificationData Data specific to the notification class @param int|null $priority The notification priority (bigger values for higher priorities) @return static
entailment
public function setSentCountPotential($value = null) { if ($value === null || $value === '' || $value === false) { $this->sentCountPotential = null; } else { $this->sentCountPotential = (int) $value; } return $this; }
Set the number of actual recipients notified (null if not yed delivered). @param int|null $value @return static
entailment
public function setSentCountActual($value = null) { if ($value === null || $value === '' || $value === false) { $this->sentCountActual = null; } else { $this->sentCountActual = (int) $value; } return $this; }
Set the number of actual recipients notified (null if not yed delivered). @param int|null $value @return static
entailment
public function format($user) { $id = null; $name = ''; $userInfo = null; if (isset($user) && $user) { if (is_int($user) || (is_string($user) && is_numeric($user))) { $user = \User::getByUserID($user); } try { if ($user instanceof ConcreteUser && $user->getUserID() && $user->isRegistered()) { $id = (int) $user->getUserID(); $name = $user->getUserName(); } elseif ($user instanceof UserInfo && $user->getUserID()) { $id = (int) $user->getUserID(); $name = $user->getUserName(); $userInfo = $user; } elseif ($user instanceof ConcreteUserEntity && $user->getUserID()) { $id = (int) $user->getUserID(); $name = $user->getUserName(); } } catch (EntityNotFoundException $x) { $id = null; } } if ($id === null) { $result = '<i class="comtra-user comtra-user-removed">' . t('removed user') . '</i>'; } elseif ($id == USER_SUPER_ID) { $result = '<i class="comtra-user comtra-user-system">' . t('system') . '</i>'; } else { $profileURL = null; if ($userInfo === null) { $userInfo = $this->app->make(UserInfoRepository::class)->getByID($id); } if ($userInfo !== null) { $profileURL = $userInfo->getUserPublicProfileUrl(); } if ($profileURL === null) { $result = '<span'; } else { $result = '<a href="' . h((string) $profileURL) . '"'; } $result .= ' class="comtra-user comtra-user-found">' . h($name); if ($profileURL === null) { $result .= '</span>'; } else { $result .= '</a>'; } } return $result; }
Format a username. @param int|ConcreteUser|UserInfo|ConcreteUserEntity $user @return string
entailment
public function send(Nette\Http\IRequest $httpRequest, Nette\Http\IResponse $httpResponse): void { $httpResponse->setContentType($this->getContentType(), 'utf-8'); $httpResponse->setExpiration(FALSE); $httpResponse->setCode($this->code); echo Nette\Utils\Json::encode($this->getPayload(), Nette\Utils\Json::PRETTY); }
{inheritDoc}
entailment
public function getStickyRequest() { if ($this->stickyRequest === null) { $this->stickyRequest = $this->app->make(StickyRequest::class, ['community_translation.packages']); } return $this->stickyRequest; }
Get the instance of a class that holds the criteria of the last performed search. @return StickyRequest
entailment
public function getSearchList() { if ($this->searchList === null) { $this->searchList = $this->app->make(SearchList::class, [$this->getStickyRequest()]); } return $this->searchList; }
Get the instance of a class that defines the search list. @return SearchList
entailment
public function search($reset = false) { $stickyRequest = $this->getStickyRequest(); $searchList = $this->getSearchList(); if ($reset) { $stickyRequest->resetSearchRequest(); } $req = $stickyRequest->getSearchRequest(); $req = $stickyRequest->getSearchRequest(); if (isset($req['keywords']) && $req['keywords'] !== '') { $searchList->filterByKeywords($req['keywords']); } if (isset($req['locale']) && is_string($req['locale']) && $req['locale'] !== '') { $repo = $this->app->make(LocaleRepository::class); $locale = $repo->findApproved($req['locale']); if ($locale !== null) { $searchList->showLocaleStats($locale); } } $this->searchResult = new SearchResult($searchList); }
Perform the search. @param bool $reset Should we reset all the previous search criteria?
entailment
public function validateFile(FileReport $report) { $realPath = $report->getFile()->getRealPath(); if (false === is_file($realPath)) { $report->reportProblem('file not found: ' . $realPath); return false; } if (false === is_readable($realPath)) { $report->reportProblem('file not readable: ' . $realPath); return false; } libxml_clear_errors(); $domDoc = new \DOMDocument(); $domDoc->load($realPath, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_PEDANTIC); $errors = libxml_get_errors(); foreach ($this->formatter->formatErrors($errors) as $problem) { $report->reportProblem($problem); } return !$report->hasProblems(); }
{@inheritdoc}
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $this->setCommand( $this->getApplication()->find(LintCommand::COMMAND_NAME) ); parent::execute($input, $output); }
{@inheritdoc}
entailment
protected function getRecipientIDs(NotificationEntity $notification) { $result = []; $notificationData = $notification->getNotificationData(); $locale = $this->app->make(LocaleRepository::class)->findApproved($notificationData['localeID']); if ($locale === null) { throw new Exception(t('Unable to find the locale with ID %s', $notificationData['localeID'])); } $uir = $this->app->make(UserInfoRepository::class); $applicantUser = $uir->getByID($notificationData['applicantUserID']); if ($applicantUser === null) { throw new Exception(t('Unable to find the user with ID %s', $notificationData['applicantUserID'])); } /* @var UserInfo $applicantUser */ if (!$applicantUser->getUserObject()->inGroup($this->getGroupsHelper()->getAspiringTranslators($locale))) { throw new Exception(t( 'The user %1$s is no more in the aspiring translators of %2$s', sprintf('%s (%s)', $applicantUser->getUserName(), $applicantUser->getUserID()), $locale->getDisplayName() )); } $group = $this->getGroupsHelper()->getAdministrators($locale); $result = array_merge($result, $group->getGroupMemberIDs()); $group = $this->getGroupsHelper()->getGlobalAdministrators(); $result = array_merge($result, $group->getGroupMemberIDs()); return $result; }
{@inheritdoc} @see Category::getRecipientIDs()
entailment
public function getMailParameters(NotificationEntity $notification, UserInfo $recipient) { $notificationData = $notification->getNotificationData(); $locale = $this->app->make(LocaleRepository::class)->findApproved($notificationData['localeID']); if ($locale === null) { throw new Exception(t('Unable to find the locale with ID %s', $notificationData['localeID'])); } $uir = $this->app->make(UserInfoRepository::class); $applicant = $uir->getByID($notificationData['applicantUserID']); if ($applicant === null) { throw new Exception(t('Unable to find the user with ID %s', $notificationData['applicantUserID'])); } return [ 'localeName' => $locale->getDisplayName(), 'applicant' => $applicant, 'teamsUrl' => $this->getBlockPageURL('CommunityTranslation Team List', 'details/' . $locale->getID()), ] + $this->getCommonMailParameters($notification, $recipient); }
{@inheritdoc} @see Category::getMailParameters()
entailment
public static function create($handle, $version, $archiveUrl) { $result = new static(); $result->id = null; $result->handle = (string) $handle; $result->name = ''; $result->url = ''; $result->approved = true; $result->version = (string) $version; $result->archiveUrl = (string) $archiveUrl; $result->createdOn = new DateTime(); $result->processedOn = null; $result->failCount = 0; $result->lastError = ''; return $result; }
@param string $handle @param string $version @param string $archiveUrl @return static
entailment
public function getByHandle($handle) { return isset($this->converters[$handle]) ? $this->converters[$handle] : null; }
Get a converter given its handle. @param string $handle @return ConverterInterface|null
entailment
public function getByFileExtension($fileExtension) { $fileExtension = ltrim($fileExtension); $result = []; foreach ($this->converters as $converter) { if (strcasecmp($fileExtension, $converter->getFileExtension()) === 0) { $result[] = $converter; } } return $result; }
Get the converter given a file extension. @param string $fileExtension @return ConverterInterface[]
entailment
public function getRegisteredConverters() { $result = $this->converters; $comparer = new Comparer(); usort($result, function (ConverterInterface $a, ConverterInterface $b) use ($comparer) { return $comparer->compare($a->getName(), $b->getName()); }); return $result; }
Get the list of registered converters. @throws UserMessageException @return ConverterInterface[]
entailment
public function filterByKeywords($name) { $likeBuilder = $this->app->make(LikeBuilder::class); /* @var LikeBuilder $likeBuilder */ $likes = $likeBuilder->splitKeywordsForLike($name, '\W_'); if (!empty($likes)) { $expr = $this->query->expr(); $orFields = $expr->orX(); foreach (['p.handle', 'p.name'] as $fieldName) { $and = $expr->andX(); foreach ($likes as $like) { $and->add($expr->like($fieldName, $this->query->createNamedParameter($like))); } $orFields->add($and); } $this->query->andWhere($orFields); } }
Filter the results by keywords. @param string $name
entailment
public function getTotalResults() { $query = $this->deliverQueryObject(); $query ->resetQueryParts(['groupBy', 'orderBy']) ->select('count(distinct p.id)') ->setMaxResults(1); $result = $query->execute()->fetchColumn(); return (int) $result; }
{@inheritdoc} @see \Concrete\Core\Search\ItemList\ItemList::getTotalResults()
entailment
protected function createPaginationObject() { $adapter = new DoctrineDbalAdapter( $this->deliverQueryObject(), function (\Doctrine\DBAL\Query\QueryBuilder $query) { $query ->resetQueryParts(['groupBy', 'orderBy']) ->select('count(distinct p.id)') ->setMaxResults(1); } ); $pagination = new Pagination($this, $adapter); return $pagination; }
{@inheritdoc} @see \Concrete\Core\Search\ItemList\ItemList::createPaginationObject()
entailment
public function getResult($queryRow) { $result = null; $entityManager = $this->getEntityManager(); $package = $entityManager->find(PackageEntity::class, $queryRow['id']); if ($package !== null) { $result = [$package]; if ($this->localeStats !== null) { $pv = $package->getLatestVersion(); if ($pv !== null) { $result[] = $this->getStats()->getOne($pv, $this->localeStats); } else { $result[] = false; } } } return $result; }
{@inheritdoc} @see \Concrete\Core\Search\ItemList\ItemList::getResult()
entailment