code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
protected function validateField($fieldName, $value) { if (!$this->validateValue($value)) { $this->validationError( $fieldName, _t( __CLASS__ . '.InvalidValue', 'Synonyms cannot contain words separated by spaces' ) ); } }
Validate field values, raising errors if the values are invalid. @param string $fieldName @param mixed $value
protected function validateValue($value) { // strip empty lines $lines = array_filter( explode("\n", $value) ); // strip comments (lines beginning with "#") $lines = array_filter($lines, function ($line) { $line = trim($line); return !empty($line) && $line[0] !== '#'; }); // validate each line foreach ($lines as $line) { if (!$this->validateLine($line)) { return false; } } return true; }
Check field values to see that they doesn't contain spaces between words. @param mixed $value @return bool
protected function validateLine($line) { $line = trim($line); $parts = explode(',', $line); $parts = array_filter($parts); foreach ($parts as $part) { if (!$this->validatePart($part)) { return false; } } return true; }
Check each line to see that it doesn't contain spaces between words. @param string $line @return bool
protected function validatePart($part) { if (strpos($part, '=>') !== false) { $subs = explode('=>', $part); $subs = array_filter($subs); foreach ($subs as $sub) { if (!$this->validateNoSpaces($sub)) { return false; } } return true; } return $this->validateNoSpaces($part); }
Check each part of the line doesn't contain spaces between words. @param string $part @return bool
public static function isHash(array $value) { $expectedKey = 0; foreach ($value as $key => $val) { if ($key !== $expectedKey++) { return true; } } return false; }
Check if given array is hash or just normal indexed array. @internal @param array $value The PHP array to check @return bool true if value is hash array, false otherwise
private static function parseQuotedScalar($scalar, &$i) { if (!Parser::preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) { throw new ParseException(sprintf('Malformed inline YAML string: %s.', substr($scalar, $i))); } $output = substr($match[0], 1, strlen($match[0]) - 2); $unescaper = new Unescaper(); if ('"' == $scalar[$i]) { $output = $unescaper->unescapeDoubleQuotedString($output); } else { $output = $unescaper->unescapeSingleQuotedString($output); } $i += strlen($match[0]); return $output; }
Parses a YAML quoted scalar. @param string $scalar @param int &$i @return string @throws ParseException When malformed inline YAML string is parsed
public function create(array $note, array $options = array()) { $attributes = array_intersect_key($note, array_flip(self::$keysToPersist)); list($code, $createdNote) = $this->httpClient->post("/notes", $attributes, $options); return $createdNote; }
Create a note post '/notes' Create a new note and associate it with one of the resources listed below: * [Leads](/docs/rest/reference/leads) * [Contacts](/docs/rest/reference/contacts) * [Deals](/docs/rest/reference/deals) @param array $note This array's attributes describe the object to be created. @param array $options Additional request's options. @return array The resulting object representing created resource.
public function update($id, array $note, array $options = array()) { $attributes = array_intersect_key($note, array_flip(self::$keysToPersist)); list($code, $updatedNote) = $this->httpClient->put("/notes/{$id}", $attributes, $options); return $updatedNote; }
Update a note put '/notes/{id}' Updates note information If the note ID does not exist, this request will return an error @param integer $id Unique identifier of a Note @param array $note This array's attributes describe the object to be updated. @param array $options Additional request's options. @return array The resulting object representing updated resource.
public function isValid() { if (!is_string($this->accessToken)) { $msg = 'Provided access token is invalid as it is not a string'; throw new Errors\ConfigurationError($msg); } if (preg_match('/\s/', $this->accessToken)) { $msg = 'Provided access token is invalid ' . 'as it contains disallowed characters. ' . 'Please double-check your access token.'; throw new Errors\ConfigurationError($msg); } if (strlen($this->accessToken) != 64) { $msg = 'Provided access token is invalid ' . 'as it contains disallowed characters. ' . 'Please double-check your access token.'; throw new Errors\ConfigurationError($msg); } if (!is_string($this->baseUrl) || !preg_match(Configuration::URL_REGEXP, $this->baseUrl)) { $msg = 'Provided base url is invalid ' . 'as it is not a valid URI. ' . 'Please make sure it includes the schema part, both http and https are accepted, ' . 'and the hierarchical part.'; throw new Errors\ConfigurationError($msg); } return true; }
Checks if provided configuration is valid. @throws \BaseCRM\Errors\ConfigurationError if provided access token is invalid - contains disallowed characters @throws \BaseCRM\Errors\ConfigurationError if provided access token is invalid - has invalid length @throws \BaseCRM\Errors\ConfigurationError if provided base url is invalid @return boolean
public static function configure() { if (!class_exists(Solr::class)) { return; } // get options from configuration $options = static::config()->get('options'); // get version specific options switch ($options['version']) { case 'cwp-4': $solrOptions = self::options_for_cwp($options); break; case 'local-4': $solrOptions = self::options_for_local($options); break; default: throw new InvalidArgumentException(sprintf( 'Solr version "%s" is not supported on CWP. Please use "local-4" on local ' . 'and "cwp-4" on production. For preferred configuration see ' . 'https://www.cwp.govt.nz/developer-docs/.', $options['version'] )); break; } // Allow users to override extras path. // CAUTION: CWP does not permit usage of customised solrconfig.xml. if (isset($options['extraspath']) && file_exists($options['extraspath'])) { $solrOptions['extraspath'] = $options['extraspath']; } elseif (file_exists(BASE_PATH . '/app/conf/extras')) { $solrOptions['extraspath'] = BASE_PATH . '/app/conf/extras'; } Solr::configure_server($solrOptions); }
Configure Solr. $options - An array consisting of: 'extraspath' - (String) Where to find Solr core configuartion files. Defaults to '<BASE_PATH>/app/conf/extras'. 'version' - select the Solr configuration to use when in CWP. One of: * 'cwp-4': preferred version, uses secured 4.x service available on CWP * 'local-4': this can be use for development using silverstripe-localsolr package, 4.x branch
protected function decode($var) { $lines = (array) preg_split('#(\r\n|\n|\r)#', $var); $results = array(); foreach ($lines as $line) { preg_match('#^\[(.*)\] (.*) @ (.*) @@ (.*)$#', $line, $matches); if ($matches) { $results[] = ['date' => $matches[1], 'message' => $matches[2], 'url' => $matches[3], 'file' => $matches[4]]; } } return $results; }
Decode RAW string into contents. @param string $var @return array mixed
public function addPath($scheme, $prefix, $paths, $override = false, $force = false) { $list = []; foreach((array) $paths as $path) { if (\is_array($path)) { // Support stream lookup in ['theme', 'path/to'] format. if (\count($path) !== 2 || !\is_string($path[0]) || !\is_string($path[1])) { throw new \BadMethodCallException('Invalid stream path given.'); } $list[] = $path; } elseif (false !== strpos($path, '://')) { // Support stream lookup in 'theme://path/to' format. $stream = explode('://', $path, 2); $stream[1] = trim($stream[1], '/'); $list[] = $stream; } else { // Normalize path. $path = rtrim(str_replace('\\', '/', $path), '/'); if ($force || @file_exists("{$this->base}/{$path}") || @file_exists($path)) { // Support for absolute and relative paths. $list[] = $path; } } } if (isset($this->schemes[$scheme][$prefix])) { $paths = $this->schemes[$scheme][$prefix]; if (!$override || $override == 1) { $list = $override ? array_merge($paths, $list) : array_merge($list, $paths); } else { $location = array_search($override, $paths, true) ?: \count($paths); array_splice($paths, $location, 0, $list); $list = $paths; } } $this->schemes[$scheme][$prefix] = $list; // Sort in reverse order to get longer prefixes to be matched first. krsort($this->schemes[$scheme]); $this->cache = []; }
Add new paths to the scheme. @param string $scheme @param string $prefix @param string|array $paths @param bool|string $override True to add path as override, string @param bool $force True to add paths even if them do not exist. @throws \BadMethodCallException
public function getPaths($scheme = null) { return !$scheme ? $this->schemes : (isset($this->schemes[$scheme]) ? $this->schemes[$scheme] : []); }
Return all scheme lookup paths. @param string $scheme @return array
public function isStream($uri) { try { list ($scheme,) = $this->normalize($uri, true, true); } catch (\Exception $e) { return false; } return $this->schemeExists($scheme); }
Returns true if uri is resolvable by using locator. @param string $uri @return bool
public function normalize($uri, $throwException = false, $splitStream = false) { if (!\is_string($uri)) { if ($throwException) { throw new \BadMethodCallException('Invalid parameter $uri.'); } return false; } $uri = preg_replace('|\\\|u', '/', $uri); $segments = explode('://', $uri, 2); $path = array_pop($segments); $scheme = array_pop($segments) ?: 'file'; if ($path) { $path = preg_replace('|\\\|u', '/', $path); $parts = explode('/', $path); $list = []; foreach ($parts as $i => $part) { if ($part === '..') { $part = array_pop($list); if ($part === null || $part === '' || (!$list && strpos($part, ':'))) { if ($throwException) { throw new \BadMethodCallException('Invalid parameter $uri.'); } return false; } } elseif (($i && $part === '') || $part === '.') { continue; } else { $list[] = $part; } } if (($l = end($parts)) === '' || $l === '.' || $l === '..') { $list[] = ''; } $path = implode('/', $list); } return $splitStream ? [$scheme, $path] : ($scheme !== 'file' ? "{$scheme}://{$path}" : $path); }
Returns the canonicalized URI on success. The resulting path will have no '/./' or '/../' components. Trailing delimiter `/` is kept. By default (if $throwException parameter is not set to true) returns false on failure. @param string $uri @param bool $throwException @param bool $splitStream @return string|array|bool @throws \BadMethodCallException
public function findResource($uri, $absolute = true, $first = false) { if (!\is_string($uri)) { throw new \BadMethodCallException('Invalid parameter $uri.'); } return $this->findCached($uri, false, $absolute, $first); }
Find highest priority instance from a resource. @param string $uri Input URI to be searched. @param bool $absolute Whether to return absolute path. @param bool $first Whether to return first path even if it doesn't exist. @throws \BadMethodCallException @return string|bool
public function findResources($uri, $absolute = true, $all = false) { if (!\is_string($uri)) { throw new \BadMethodCallException('Invalid parameter $uri.'); } return $this->findCached($uri, true, $absolute, $all); }
Find all instances from a resource. @param string $uri Input URI to be searched. @param bool $absolute Whether to return absolute path. @param bool $all Whether to return all paths even if they don't exist. @throws \BadMethodCallException @return array
public function mergeResources(array $uris, $absolute = true, $all = false) { $uris = array_unique($uris); $lists = [[]]; foreach ($uris as $uri) { $lists[] = $this->findResources($uri, $absolute, $all); } // TODO: In PHP 5.6+ use array_merge(...$list); return call_user_func_array('array_merge', $lists); }
Find all instances from a list of resources. @param array $uris Input URIs to be searched. @param bool $absolute Whether to return absolute path. @param bool $all Whether to return all paths even if they don't exist. @throws \BadMethodCallException @return array
public function fillCache($uri) { $cacheKey = $uri . '@cache'; if (!isset($this->cache[$cacheKey])) { $this->cache[$cacheKey] = true; $iterator = new \RecursiveIteratorIterator($this->getRecursiveIterator($uri), \RecursiveIteratorIterator::SELF_FIRST); /** @var UniformResourceIterator $uri */ foreach ($iterator as $item) { $key = $item->getUrl() . '@010'; $this->cache[$key] = $item->getPathname(); } } return $this; }
Pre-fill cache by a stream. @param string $uri @return $this
public function clearCache($uri = null) { if ($uri) { $this->clearCached($uri, true, true, true); $this->clearCached($uri, true, true, false); $this->clearCached($uri, true, false, true); $this->clearCached($uri, true, false, false); $this->clearCached($uri, false, true, true); $this->clearCached($uri, false, true, false); $this->clearCached($uri, false, false, true); $this->clearCached($uri, false, false, false); } else { $this->cache = []; } return $this; }
Reset locator cache. @param string $uri @return $this
protected function find($scheme, $file, $array, $absolute, $all) { if (!isset($this->schemes[$scheme])) { throw new \InvalidArgumentException("Invalid resource {$scheme}://"); } $results = $array ? [] : false; foreach ($this->schemes[$scheme] as $prefix => $paths) { if ($prefix && strpos($file, $prefix) !== 0) { continue; } // Remove prefix from filename. $filename = '/' . trim(substr($file, \strlen($prefix)), '\/'); foreach ($paths as $path) { if (\is_array($path)) { // Handle scheme lookup. $relPath = trim($path[1] . $filename, '/'); $found = $this->find($path[0], $relPath, $array, $absolute, $all); if ($found) { if (!$array) { return $found; } $results = array_merge($results, $found); } } else { // TODO: We could provide some extra information about the path to remove preg_match(). // Check absolute paths for both unix and windows if (!$path || !preg_match('`^/|\w+:`', $path)) { // Handle relative path lookup. $relPath = trim($path . $filename, '/'); $fullPath = $this->base . '/' . $relPath; } else { // Handle absolute path lookup. $fullPath = rtrim($path . $filename, '/'); if (!$absolute) { throw new \RuntimeException("UniformResourceLocator: Absolute stream path with relative lookup not allowed ({$prefix})", 500); } } if ($all || file_exists($fullPath)) { $current = $absolute ? $fullPath : $relPath; if (!$array) { return $current; } $results[] = $current; } } } } return $results; }
@param string $scheme @param string $file @param bool $array @param bool $absolute @param bool $all @throws \InvalidArgumentException @return array|string|bool @internal
public function process(ContainerBuilder $container) { $def = $container->getDefinition('zicht_admin.event_propagator'); foreach ($container->findTaggedServiceIds('zicht_admin.event_propagation') as $id => $attributes) { foreach ($attributes as $attribute) { $def->addTag('kernel.event_listener', array('event' => $attribute['event'], 'method' => 'onEvent')); $def->addMethodCall('registerPropagation', array($attribute['event'], new Reference($id))); } } }
Process @param ContainerBuilder $container
public function transform($value) { try { return array( 'id' => (null !== $value ? $value->getId() : null), 'value' => (null !== $value ? $value->__toString() : null) ); } catch (EntityNotFoundException $e) { return ['id' => null, 'value' => '-- ENTITY NOT FOUND --']; } }
Transform the class into an hash containing 'id' and 'value' (string repr of the object). @param mixed $value @return array|mixed
public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); if (isset($config['quicklist'])) { $loader->load('quicklist.xml'); foreach ($config['quicklist'] as $name => $quicklistConfig) { $container->getDefinition('zicht_admin.quicklist') ->addMethodCall('addRepositoryConfig', array($name, $quicklistConfig)); $formResources = $container->getParameter('twig.form.resources'); $formResources[]= 'ZichtAdminBundle::form_theme.html.twig'; $container->setParameter('twig.form.resources', $formResources); } } if (isset($config['transactional_listener']) && $config['transactional_listener']['auto']) { $loader->load('transactional_listener.xml'); $container->getDefinition('zicht_admin.transactional_listener') ->addArgument($config['transactional_listener']['pattern']); } if (isset($config['rc'])) { $loader->load('rc.xml'); $container->getDefinition('zicht_admin.controller.rc')->replaceArgument(0, $config['rc']); } $container->getDefinition('zicht_admin.security.authorization.voter.admin_voter') ->replaceArgument(0, $config['security']['mapped_attributes']); }
Load @param array $configs @param ContainerBuilder $container
public function duplicateAction() { $id = $this->getRequest()->get($this->admin->getIdParameter()); $object = $this->admin->getObject($id); if (!$object) { throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id)); } if (false === $this->admin->isGranted('DUPLICATE', $object)) { throw new AccessDeniedException(); } $newObject = clone $object; if (method_exists($newObject, 'setTitle')) { $newObject->setTitle('[COPY] - ' . $newObject->getTitle()); } $objectManager = $this->getDoctrine()->getManager(); $objectManager->persist($newObject); $objectManager->flush(); $this->addFlash( 'sonata_flash_success', $this->admin->trans('flash_duplicate_success') ); return new RedirectResponse($this->admin->generateObjectUrl('edit', $newObject)); }
Duplicate pages @return RedirectResponse @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
public function moveUpAction($id) { $repo = $this->getDoctrine()->getManager()->getRepository($this->admin->getClass()); $result = $repo->find($id); $repo->moveUp($result); if ($referer = $this->getRequest()->headers->get('referer')) { return $this->redirect($referer); } else { return new Response('<script>history.go(-1);</script>'); } }
Move the item up. Used for Tree admins @param mixed $id @return \Symfony\Component\HttpFoundation\Response
protected function bindAndRender($action) { // the key used to lookup the template $templateKey = 'edit'; if ($action == 'edit') { $id = $this->getRequest()->get($this->admin->getIdParameter()); $object = $this->admin->getObject($id); if (!$object) { throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id)); } if (false === $this->admin->isGranted('EDIT', $object)) { throw new AccessDeniedException(); } } else { $object = $this->admin->getNewInstance(); $this->admin->setSubject($object); /** @var $form \Symfony\Component\Form\Form */ $form = $this->admin->getForm(); $form->setData($object); } $this->admin->setSubject($object); /** @var $form \Symfony\Component\Form\Form */ $form = $this->admin->getForm(); $form->setData($object); if ($this->getRequest()->getMethod() == 'POST') { $form->handleRequest($this->getRequest()); } $view = $form->createView(); // set the theme for the current Admin Form $this->get('twig')->getRuntime(FormRenderer::class)->setTheme($view, $this->admin->getFormTheme()); return $this->render( $this->admin->getTemplate($templateKey), array( 'action' => $action, 'form' => $view, 'object' => $object, ) ); }
Binds the request to the form and only renders the resulting form. @param string $action @return \Symfony\Component\HttpFoundation\Response @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('zicht_admin'); $rootNode ->children() ->arrayNode('security') ->addDefaultsIfNotSet() ->children() ->arrayNode('mapped_attributes') ->prototype('scalar')->end() ->defaultValue(['EDIT', 'DELETE', 'VIEW', 'CREATE', 'ADMIN']) ->end() ->end() ->end() ->arrayNode('transactional_listener') ->addDefaultsIfNotSet() ->children() ->booleanNode('auto')->defaultTrue()->end() ->scalarNode('pattern') ->defaultValue('!^/admin.*(edit|delete|create|move)!') ->validate() ->ifTrue( function ($p) { return (false === preg_match($p, '')); } )->thenInvalid("Invalid PCRE pattern") ->end() ->end() ->end() ->end() ->arrayNode('quicklist') ->prototype('array') ->children() ->scalarNode('repository')->end() ->scalarNode('title')->end() ->arrayNode('fields')->prototype('scalar')->end()->end() ->scalarNode('name')->end() ->booleanNode('exposed')->defaultValue(false)->end() ->end() ->end() ->useAttributeAsKey('name') ->end() ->arrayNode('rc') ->prototype('array') ->addDefaultsIfNotSet() ->children() ->scalarNode('name')->end() ->scalarNode('mode')->defaultValue("trigger")->end() ->scalarNode('route')->end() ->arrayNode('route_params')->prototype('variable')->end()->defaultValue([])->end() ->scalarNode('method')->defaultValue(null)->end() ->scalarNode('title')->end() ->scalarNode('button')->end() ->end() ->end() ->useAttributeAsKey('name') ->end() ->end(); return $treeBuilder; }
{@inheritDoc}
public function createQuery($context = 'list') { if ($context === 'list') { /** @var $em \Doctrine\ORM\EntityManager */ $em = $this->getModelManager()->getEntityManager($this->getClass()); /** @var $cmd \Doctrine\Common\Persistence\Mapping\ClassMetadata */ $cmd = $em->getMetadataFactory()->getMetadataFor($this->getClass()); $queryBuilder = $em->createQueryBuilder(); $queryBuilder ->select('n') ->from($this->getClass(), 'n'); if ($cmd->hasField('root')) { $queryBuilder->orderBy('n.root, n.lft'); } else { $queryBuilder->orderBy('n.lft'); } return new ProxyQuery($queryBuilder); } return parent::createQuery($context); }
Override the default query builder to utilize correct sorting @param string $context @return ProxyQueryInterface
protected function configureRoutes(RouteCollection $collection) { parent::configureRoutes($collection); $collection->add('moveUp', $this->getRouterIdParameter() . '/move-up'); $collection->add('moveDown', $this->getRouterIdParameter() . '/move-down'); }
Configure route @param RouteCollection $collection
public function filterWithChildren($qb, $alias, $field, $value) { // Check whether it is a numeric value because we could get a string number. if (!($value['value'] && is_numeric($value['value']))) { return null; } // Get the parent item $parentQb = clone $qb; $parentQb->where($parentQb->expr()->eq(sprintf('%s.id', $alias), ':id')); $parentQb->setParameter('id', (int)$value['value']); $currentItem = $parentQb->getQuery()->getOneOrNullResult(); if ($currentItem === null) { return null; } $qb->where( $qb->expr()->andX( $qb->expr()->eq(sprintf('%s.root', $alias), ':root'), $qb->expr()->orX( $qb->expr()->andX( $qb->expr()->lt(sprintf('%s.lft', $alias), ':left'), $qb->expr()->gt(sprintf('%s.rgt', $alias), ':right') ), $qb->expr()->between(sprintf('%s.lft', $alias), ':left', ':right') ) ) ); $qb->setParameter('root', $currentItem->getRoot()); $qb->setParameter('left', $currentItem->getLft()); $qb->setParameter('right', $currentItem->getRgt()); return true; }
Get item plus children @param \Doctrine\ORM\QueryBuilder $qb @param string $alias @param string $field @param array $value @return bool|null
public function vote(TokenInterface $token, $object, array $attributes) { // check if class of this object is supported by this voter if (!is_null($object) && $this->supportsClass(get_class($object))) { $class = get_class($object); /** @var AccessDecisionManagerInterface $accessDecisionManager */ $accessDecisionManager = $this->decisionManager; foreach ($this->mapAttributesToRoles($class, $attributes) as $mappedAttr) { if ($accessDecisionManager->decide($token, array($mappedAttr), $object)) { return VoterInterface::ACCESS_GRANTED; } } } return VoterInterface::ACCESS_ABSTAIN; }
Vote @param TokenInterface $token @param null|object $object @param array $attributes @return int
protected function mapAttributesToRoles($class, $attributes) { $mappedAttributes = array(); foreach ($this->pool->getAdminClasses() as $adminClass => $adminCodes) { if ($class === $adminClass || $class instanceof $adminClass) { foreach ($adminCodes as $adminCode) { $admin = $this->pool->getAdminByAdminCode($adminCode); $baseRole = $this->securityHandler->getBaseRole($admin); foreach ($attributes as $attr) { if ($this->supportsAttribute($attr)) { $mappedAttributes[] = sprintf($baseRole, $attr); } } } } } return $mappedAttributes; }
Maps regular attributes such as VIEW, EDIT, etc, to their respective SONATA role name, such as ROLE_FOO_BAR_BAZ_EDIT @param string $class @param string[] $attributes @return array
public function adminUrl($subject, $action, $parameters = array()) { if (is_object($subject)) { $className = get_class($subject); } elseif (is_string($subject)) { $className = $subject; if (strpos($className, ':') !== false) { list($namespace, $entity) = explode(':', $className); $className = $this->doctrine->getAliasNamespace($namespace) . '\\' . $entity; } } else { throw new InvalidArgumentException("Unsupported subject, need either an object or a string"); } /** @var $admin \Sonata\AdminBundle\Admin\Admin */ $admin = $this->sonata->getAdminByClass($className); if (!$admin) { // assume the string is an admincode. $admin = $this->sonata->getAdminByAdminCode($className); } if (!$admin) { throw new InvalidArgumentException("No admin found for {$className}"); } if (is_object($subject)) { return $admin->generateObjectUrl($action, $subject, $parameters); } else { return $admin->generateUrl($action, $parameters); } }
Render an url to a sonata admin @param mixed $subject @param string $action @param array $parameters @return string @throws InvalidArgumentException
public function onKernelRequest(KernelEvent $event) { // TODO explicit transaction management in stead of this. See ZICHTDEV-119 for ideas on this if ($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST && preg_match($this->pattern, $event->getRequest()->getRequestUri())) { $this->wasTxStarted = true; $this->doctrine->getConnection()->beginTransaction(); } }
Starts a transaction within any url matching the constructor's $pattern parameter @param \Symfony\Component\HttpKernel\Event\KernelEvent $event @return void
public function onKernelResponse(KernelEvent $event) { if ($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST && $this->wasTxStarted && $this->doctrine->getConnection()->getTransactionIsolation() > 0) { if ($this->doctrine->getConnection()->isRollbackOnly()) { $this->doctrine->getConnection()->rollback(); } else { $this->doctrine->getConnection()->commit(); } $this->wasTxStarted = false; } }
Commits the transaction, if started @param \Symfony\Component\HttpKernel\Event\KernelEvent $event @return void
public function quicklistAction(Request $request) { $quicklist = $this->get('zicht_admin.quicklist'); if ($request->get('repo') && $request->get('pattern')) { if ($request->get('language')) { $language = $request->get('language'); } else { $language = null; } return new JsonResponse($quicklist->getResults($request->get('repo'), $request->get('pattern'), $language)); } return array( 'repos' => $quicklist->getRepositoryConfigs() ); }
Displays a quick list control for jumping to entries registered in the quick list service @param Request $request @return array|JsonResponse @Template("@ZichtAdmin/Quicklist/quicklist.html.twig") @Route("quick-list")
public function onEvent(Event $anyEvent, $eventName, EventDispatcherInterface $dispatcher) { if (isset($this->propagations[$eventName])) { foreach ($this->propagations[$eventName] as $builder) { $builder->buildAndForwardEvent($anyEvent); } } }
Builds and forwards the event for all progragations registered for the specified event type. @param \Symfony\Component\EventDispatcher\Event $anyEvent @param string $eventName @param EventDispatcherInterface $dispatcher @return void
public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); $transformerStrategy = $options['transformer']; if ($transformerStrategy === 'auto') { $transformerStrategy = $options['multiple'] ? 'multiple' : 'class'; } switch ($transformerStrategy) { case 'class': $builder->addViewTransformer(new ClassTransformer($this->quicklist, $options['repo'])); break; case 'none': $builder->addViewTransformer(new NoneTransformer($this->quicklist, $options['repo'])); break; case 'multiple': $builder->addViewTransformer(new MultipleTransformer(new ClassTransformer($this->quicklist, $options['repo']))); break; case 'multiple_none': $builder->addViewTransformer(new MultipleTransformer(new NoneTransformer($this->quicklist, $options['repo']))); break; } }
Build forms @param FormBuilderInterface $builder @param array $options
public function getRepositoryConfigs($exposedOnly = true) { if ($exposedOnly) { return array_filter( $this->repos, function ($item) { return isset($item['exposed']) && $item['exposed'] === true; } ); } return $this->repos; }
Returns all configurations @param bool $exposedOnly @return array
private function getFirstAdminPerClass($class) { $code = null; $admins = $this->adminPool->getAdminClasses(); foreach ($admins as $key => $value) { if ($key === $class) { $code = current($value); break; } } return $code === null ? $this->adminPool->getAdminByClass($class) : $this->adminPool->getAdminByAdminCode($code); }
Gets the first admin when there are multiple definitions. @param string $class @return null|\Sonata\AdminBundle\Admin\AdminInterface
public function getResults($repository, $pattern, $language = null, $max = 15) { $queryResults = $this->findRecords($repository, $pattern, $language); $results = array(); foreach ($queryResults as $record) { $admin = $this->getFirstAdminPerClass(get_class($record)); if (!$admin) { $admin = $this->getFirstAdminPerClass(get_parent_class($record)); } $resultRecord = $this->createResultRecord($record, $admin); $results[] = $resultRecord; } // TODO do this sort in DQL. Unfortunately, doctrine is not too handy with this, so // I'll keep it like this for a second. Note the the "setMaxResults()" should be reverted to $max // and the slice can be removed usort( $results, function ($a, $b) use ($pattern) { $percentA = 0; $percentB = 0; similar_text($a['label'], $pattern, $percentA); similar_text($b['label'], $pattern, $percentB); return $percentB - $percentA; } ); return array_slice($results, 0, $max); }
Get the result suggestions for the passed pattern @param string $repository @param string $pattern @param null|string $language @param int $max @return array
public function getOne($repository, $id) { $repoConfig = $this->repos[$repository]; /** @var $q \Doctrine\ORM\QueryBuilder */ return $this->doctrine ->getRepository($repoConfig['repository']) ->find($id); }
Return a single record by it's id. Used to map the front-end variable back to an object from the repository. @param string $repository @param mixed $id @return object
private function findRecords($repository, $pattern, $language = null) { $repoConfig = $this->repos[$repository]; /** @var $q \Doctrine\ORM\QueryBuilder */ $q = $this->doctrine ->getRepository($repoConfig['repository']) ->createQueryBuilder('i') ->setMaxResults(1500); $eb = $q->expr(); $expr = $eb->orX(); foreach ($repoConfig['fields'] as $fieldName) { $expr->add($eb->like($eb->lower('i.' . $fieldName), $eb->lower(':pattern'))); } $q->where($expr); $params = array('pattern' => '%' . $pattern . '%'); if (null !== $language) { $q->andWhere('i.language = :lang'); $params[':lang'] = $language; } return $q->getQuery()->execute($params); }
Find records @param string $repository @param string $pattern @param null|string $language @return mixed
public function createResultRecord($record, $admin) { $resultRecord = array( 'label' => (string)$record, 'value' => (string)$record, 'url' => ($admin ? $admin->generateObjectUrl('edit', $record) : null), 'id' => ($admin ? $admin->id($record) : null) ); return $resultRecord; }
Creates result record @param object $record @param object $admin @return array
public function addMenuItem(MenuEvent $e) { $array = $e->getMenuConfig(); $this->menu->addChild( $this->factory->createItem($array['name'], $array) ); }
Add a child to the menu @param MenuEvent $e @return void
public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass( new DependencyInjection\Compiler\EventPropagationPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION ); }
Build @param ContainerBuilder $container
public static function reorderTabs(FormMapper $formMapper, array $tabOrder) { $tabsOriginal = $formMapper->getAdmin()->getFormTabs(); //filter out tabs that doesn't exist (yet) $tabOrder = array_filter( $tabOrder, function ($key) use ($tabsOriginal) { return array_key_exists($key, $tabsOriginal); } ); $tabs = array_merge(array_flip($tabOrder), $tabsOriginal); $formMapper->getAdmin()->setFormTabs($tabs); }
Allows to reorder Tabs Need the formMapper since the used methods to set the tabs are protected in the original Sonata implementation @param FormMapper $formMapper @param array $tabOrder @return void
public function map(FormMapper $formMapper, $helpPrefix = null) { $this->formMapper = $formMapper; $this->helpPrefix = $helpPrefix; return $this; }
Start a mapping of fields on the given formMapper @param FormMapper $formMapper @param null|string $helpPrefix @return AdminUtil
public function add($name, $type = null, array $options = array(), array $fieldDescriptionOptions = array()) { if (null === $this->formMapper) { throw new LogicException('No FormMapper to add fields to, please make sure you start with AdminUtil->map'); } $this->formMapper->add($name, $type, $options, $fieldDescriptionOptions); if ($this->addHelp) { $this->formMapper->setHelps([$name => 'help' . (null !== $this->helpPrefix ? sprintf('.%s', $this->helpPrefix) : '') . '.' . $name]); } return $this; }
Add a field to the given formMapper @param string $name @param null $type @param array $options @param array $fieldDescriptionOptions @return $this
public function rename($oldName, $newName) { if (! ftp_rename($this->session, $oldName, $newName)) { throw new \RuntimeException('Name can not be changed'); } return true; }
{@inheritDoc} @throws RuntimeException
public function chmod($permission,$file) { if (! ftp_chmod($this->session, $permission, $file)) { throw new \RuntimeException('Chmod can not be changed'); } return true; }
{@inheritDoc} @throws RuntimeException
private function nList($dir) { $dirList = ftp_nlist($this->session, $dir); if ($dirList === false) { throw new \RuntimeException('List error'); } return $dirList; }
Returns a list of files in the given directory @link http://php.net/ftp_nlist @param string $dir The directory to be listed @throws RuntimeException @return array File list
public function listItem($type, $dir = '.', $recursive = false, $ignore = array()) { if ($type != 'dir' && $type != 'file') { throw new \InvalidArgumentException('$type must "file" or "dir"'); } $fileList = $this->nList($dir); $fileInfo = array(); foreach ($fileList as $file) { // remove directory and subdirectory name $file = str_replace("$dir/", '', $file); if ($this->ignoreItem($type, $file, $ignore) !== true && $this->isDirOrFile("$dir/$file") == $type) { $fileInfo[] = $file; } if ($recursive === true && $this->isDirOrFile("$dir/$file") == 'dir') { $fileInfo = array_merge($fileInfo, $this->listItem($type, "$dir/$file", $recursive, $ignore)); } } return $fileInfo; }
List of file or directory @link http://php.net/ftp_nlist Php manuel @access public @param string $dir ftp directory name @return array file list @throws FileException
public function getGeneratedXML() { $dom = new XmlDomConstruct('1.0', 'utf-8'); $dom->fromMixed(array( 'request' => $this->_args )); $post_data = $dom->saveXML(); $post_data = str_replace('<request/>', '<request method="' . $this->_method . '" />', $post_data); $post_data = str_replace('<request>', '<request method="' . $this->_method . '">', $post_data); return $post_data; }
/* Get the generated XML to view. This is useful for debugging to see what you're actually sending over the wire. Call this after $fb->post() but before your make your $fb->request() @return array
public function request() { if(!$this->domain || !$this->token) { throw new FreshBooksApiException( 'You need to call new FreshBooksApi($domain, $token) with your domain and token.' ); } $post_data = $this->getGeneratedXML(); $url = str_replace('{{ DOMAIN }}', $this->domain, $this->_api_url); $ch = curl_init(); // initialize curl handle curl_setopt($ch, CURLOPT_URL, $url); // set url to post to curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable curl_setopt($ch, CURLOPT_TIMEOUT, 40); // times out after 40s curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // add POST fields curl_setopt($ch, CURLOPT_USERPWD, $this->token . ':X'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); if(curl_errno($ch)) { $this->_error = 'A cURL error occured: ' . curl_error($ch); return; } else { curl_close($ch); } // With the new invoice.getPDF request, we sometimes have non-XML come through here if (substr($result, 0, 4) == "%PDF") { // it's a PDF file $response = $result; $this->_success = true; } else { $response = json_decode(json_encode(simplexml_load_string($result)), true); $this->_success = ($response['@attributes']['status'] == 'ok'); } $this->_response = $response; if(isset($response['error'])) { $this->_error = $response['error']; } }
/* Send the request over the wire. Return result will be binary data if the FreshBooks response is a PDF, array if it is a normal request. @return mixed
public function ls($dir = '/.', $recursive = false, $ignore = array()) { return $this->listItem('file', $dir, $recursive, $ignore); }
{@inheritDoc} @throws FileException
public function download($remote, $local) { $parseFile = $this->parseLastDirectory($remote); if (! ssh2_scp_recv($this->session, $parseFile, $local)) { throw new FileException('File can not downloaded'); } return true; }
{@inheritDoc}
public function upload($local, $remote) { $parseFile = $this->parseLastDirectory($remote); if (! ssh2_scp_send($this->session, $local, $parseFile)) { throw new FileException('File can not uploaded'); } return true; }
{@inheritDoc}
public function wget($httpFile, $remote) { if (! ini_get('allow_url_fopen')) { throw new \RuntimeException('allow_url_fopen must enabled'); } if (! $fileData = file_get_contents($httpFile)) { throw new \RuntimeException('Can nat get file content'); } $parseFile = $this->parseLastDirectory($remote); if (! file_put_contents($this->getWrapper("/$parseFile"), $fileData)) { throw new FileException('File not uploaded to ftp server'); } return true; }
Upload file to ssh server from http address @access public @param string $httpFile http file name with address @param string $remote file name to upload ssh server @return boolean true if success @throws FileException|RuntimeException
public function rm($file) { $parseFile = $this->parseLastDirectory($file); if (! ssh2_sftp_unlink($this->getSFtp(), $parseFile)) { throw new FileException('File can not deleted'); } return true; }
{@inheritDoc} @throws FileException
public function fromMixed($mixed, DOMElement $domElement = null) { $domElement = is_null($domElement) ? $this : $domElement; if (is_array($mixed)) { foreach( $mixed as $index => $mixedElement ) { if ( is_int($index) ) { if ( $index == 0 ) { $node = $domElement; } else { $node = $this->createElement($domElement->tagName); $domElement->parentNode->appendChild($node); } } else { $node = $this->createElement($index); $domElement->appendChild($node); } $this->fromMixed($mixedElement, $node); } } else { $domElement->appendChild($this->createTextNode($mixed)); } }
CONSTRUCTS ELEMENTS AND TEXTS FROM AN ARRAY OR STRING. THE ARRAY CAN CONTAIN AN ELEMENT'S NAME IN THE INDEX PART AND AN ELEMENT'S TEXT IN THE VALUE PART. IT CAN ALSO CREATES AN XML WITH THE SAME ELEMENT TAGNAME ON THE SAME LEVEL. EX: <NODES> <NODE>TEXT</NODE> <NODE> <FIELD>HELLO</FIELD> <FIELD>WORLD</FIELD> </NODE> </NODES> ARRAY SHOULD THEN LOOK LIKE: ARRAY ( "NODES" => ARRAY ( "NODE" => ARRAY ( 0 => "TEXT" 1 => ARRAY ( "FIELD" => ARRAY ( 0 => "HELLO" 1 => "WORLD" ) ) ) ) ) @PARAM MIXED $MIXED AN ARRAY OR STRING. @PARAM DOMELEMENT[OPTIONAL] $DOMELEMENT THEN ELEMENT FROM WHERE THE ARRAY WILL BE CONSTRUCT TO.
public static function build(ServerInterface $server) { if ($server instanceof SftpServer) { return new SftpDirectory($server); } elseif ($server instanceof FtpServer || $server instanceof SslServer) { return new FtpDirectory($server); } else { throw new \InvalidArgumentException('The argument is must instance of server class'); } }
Build method for Directory classes
public static function build(ServerInterface $server) { if ($server instanceof SftpServer) { return new SftpFile($server); } elseif ($server instanceof FtpServer || $server instanceof SslServer) { return new FtpFile($server); } else { throw new \InvalidArgumentException('The argument is must instance of server class'); } }
Build method for File classes
public static function createRSAKey(int $size, array $values = []): JWK { if (0 !== $size % 8) { throw new \InvalidArgumentException('Invalid key size.'); } if (384 > $size) { throw new \InvalidArgumentException('Key length is too short. It needs to be at least 384 bits.'); } $key = \openssl_pkey_new([ 'private_key_bits' => $size, 'private_key_type' => OPENSSL_KEYTYPE_RSA, ]); \openssl_pkey_export($key, $out); $rsa = RSAKey::createFromPEM($out); $values = \array_merge( $values, $rsa->toArray() ); return JWK::create($values); }
Creates a RSA key with the given key size and additional values. @param int $size The key size in bits @param array $values values to configure the key
public static function createECKey(string $curve, array $values = []): JWK { try { $jwk = self::createECKeyUsingOpenSSL($curve); } catch (\Exception $e) { $jwk = self::createECKeyUsingPurePhp($curve); } $values = \array_merge($values, $jwk); return JWK::create($values); }
Creates a EC key with the given curve and additional values. @param string $curve The curve @param array $values values to configure the key
public static function createFromJsonObject(string $value) { $json = \json_decode($value, true); if (!\is_array($json)) { throw new \InvalidArgumentException('Invalid key or key set.'); } return self::createFromValues($json); }
Creates a key from a Json string. @return JWK|JWKSet
public static function createFromValues(array $values) { if (\array_key_exists('keys', $values) && \is_array($values['keys'])) { return JWKSet::createFromKeyData($values); } return JWK::create($values); }
Creates a key or key set from the given input. @return JWK|JWKSet
public static function createFromSecret(string $secret, array $additional_values = []): JWK { $values = \array_merge( $additional_values, [ 'kty' => 'oct', 'k' => Base64Url::encode($secret), ] ); return JWK::create($values); }
This method create a JWK object using a shared secret.
public static function createFromKeyFile(string $file, ?string $password = null, array $additional_values = []): JWK { $values = KeyConverter::loadFromKeyFile($file, $password); $values = \array_merge($values, $additional_values); return JWK::create($values); }
This method will try to load and convert a key file into a JWK object. If the key is encrypted, the password must be set. @throws \Exception
public static function createFromKey(string $key, ?string $password = null, array $additional_values = []): JWK { $values = KeyConverter::loadFromKey($key, $password); $values = \array_merge($values, $additional_values); return JWK::create($values); }
This method will try to load and convert a key into a JWK object. If the key is encrypted, the password must be set. @throws \Exception
public static function createFromX5C(array $x5c, array $additional_values = []): JWK { $values = KeyConverter::loadFromX5C($x5c); $values = \array_merge($values, $additional_values); return JWK::create($values); }
This method will try to load and convert a X.509 certificate chain into a public key.
public function getClient($locales = array('en')) { return new Client( $this->config['client']['user_id'], $this->config['client']['license_key'], $locales, $this->config['client']['options'] ?: array() ); }
@param array $locales @return Client
public function getReader($type = 'country', $locales = array('en')) { $type = preg_replace_callback('/([A-Z])/', function ($match) { return '_'.strtolower($match[1]); }, $type); if (!isset($this->config['db'][$type])) { throw new GeoIpException( sprintf('Unknown database type %s', $type) ); } return new Reader($this->config['path'].'/'.$this->config['db'][$type], $locales); }
@param string $type @param array $locales @return Reader @throws GeoIpException
public function getRecord($ipAddress = 'me', $type = 'country', array $options = array()) { $provider = isset($options['provider']) ? $options['provider'] : 'reader'; $locales = isset($options['locales']) ? $options['locales'] : array('en'); if ('client' == $provider) { $provider = $this->getClient($locales); } else { $provider = $this->getReader($type, $locales); } $method = preg_replace_callback('/_([a-z])/', function ($match) { return strtoupper($match[1]); }, $type); if (!method_exists($provider, $method)) { throw new GeoIpException( sprintf('The method "%s" does not exist for %s', $method, get_class($provider)) ); } return $provider->{$method}($ipAddress); }
*. @param string $ipAddress @param string $type @param array $options @return City|Country|ConnectionType|Domain|Isp|AnonymousIp|Insights|Asn @throws GeoIpException
private function downloadFile($source) { $tmpFile = tempnam(sys_get_temp_dir(), 'maxmind_geoip2_'); if (strpos($source, 'tar.gz') !== false) { @rename($tmpFile, $tmpFile.'.tar.gz'); $tmpFile .= '.tar.gz'; } if (!@copy($source, $tmpFile)) { return false; } return $tmpFile; }
@param string $source @return bool|string
private function decompressFile($fileName, $outputFilePath) { if (strpos($fileName, '.tar.gz') !== false) { $tmpDir = tempnam(sys_get_temp_dir(), 'MaxMind_'); unlink($tmpDir); mkdir($tmpDir); $p = new \PharData($fileName); $p->decompress(); $tarFileName = str_replace('.gz', '', $fileName); $phar = new \PharData($tarFileName); $phar->extractTo($tmpDir); unlink($tarFileName); $files = glob($tmpDir.DIRECTORY_SEPARATOR.'*'.DIRECTORY_SEPARATOR.'*.mmdb'); if (count($files)) { @rename($files[0], $outputFilePath); } $files = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($tmpDir, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $fileinfo) { $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink'); $todo($fileinfo->getRealPath()); } rmdir($tmpDir); } else { $gz = gzopen($fileName, 'rb'); $outputFile = fopen($outputFilePath, 'wb'); while (!gzeof($gz)) { fwrite($outputFile, gzread($gz, 4096)); } fclose($outputFile); gzclose($gz); } return is_readable($outputFilePath); }
@param $fileName @param $outputFilePath @return bool
public function loadFromUrl(string $url, array $header = []): JWKSet { $content = $this->getContent($url, $header); $data = $this->jsonConverter->decode($content); if (!\is_array($data)) { throw new \RuntimeException('Invalid content.'); } $keys = []; foreach ($data as $kid => $cert) { if (false === \mb_strpos($cert, '-----BEGIN CERTIFICATE-----')) { $cert = '-----BEGIN CERTIFICATE-----'.PHP_EOL.$cert.PHP_EOL.'-----END CERTIFICATE-----'; } $jwk = KeyConverter::loadKeyFromCertificate($cert); if (\is_string($kid)) { $jwk['kid'] = $kid; $keys[$kid] = JWK::create($jwk); } else { $keys[] = JWK::create($jwk); } } return JWKSet::createFromKeys($keys); }
This method will try to fetch the url a retrieve the key set. Throws an exception in case of failure. @throws \InvalidArgumentException
public static function formatByte($byte) { // ignore "Warning: Division by zero" if ($byte == 0) { return '0 B'; } $s = array('B', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb'); $e = floor(log($byte)/log(1024)); return sprintf('%.2f '.$s[$e], ($byte/pow(1024, floor($e)))); }
Format file size to human readable @access public @param int $byte byte of file size @return strıng formatted file size
public static function newName($name) { if (file_exists($name)) { $extension = self::getFileExtension($name); $name = substr($name,0,(-strlen($extension)-1)) . '_' . sha1(uniqid(rand(), true)) . ".$extension"; } return $name; }
/* if exist local file, rename file demo.html renamed to demo_dae4c9057b2ea5c3c9e96e8352ac28f0c7d87f7d.html @access public @param string $name file name @return new file name
public function execute($command, callable $next) { try { $result = $next($command); } catch (\Exception $exception) { $this->eventRecorder->eraseEvents(); throw $exception; } $recordedEvents = $this->eventRecorder->releaseEvents(); foreach ($recordedEvents as $event) { $this->eventDispatcher->dispatch($event); } return $result; }
Dispatches all the recorded events in the EventBus and erases them @param object $command @param callable $next @return mixed @throws \Exception
private function ignoreItem($type, $name, $ignore) { if ($type == 'file' && in_array(pathinfo($name, PATHINFO_EXTENSION), $ignore)) { return true; } elseif ($type == 'dir' && in_array($name, $ignore)) { return true; } return false; }
Ignore item to itemList @access private @param string $type Type of item @param string $name Name of item @param array $ignore Names or extension item for ignore @return boolean
public function connect() { if (! $this->session = ftp_connect($this->server, $this->port, $this->timeout)) { throw new ConnectionFailedException('Could not connect to the server'); } }
{@inheritDoc}
public function getUniqueIconsList() { if ($this->uniqueIconsList === null) { $this->uniqueIconsList = $this->fetchUniqueIconsList(); } return $this->uniqueIconsList; }
Returns list of icons. @return array file path => name
public function fetchUniqueIconsList() { $md5s = []; foreach ($this->getIconsList() as $path => $name) { $hash = md5_file($path); if (in_array($hash, $md5s, true)) { continue; } $md5s[$path] = $hash; $list[$path] = $name; } return $list; }
Fetches list of unique icons. @return array
public function getIconsList() { if ($this->iconsList === null) { $this->iconsList = $this->fetchIconsList(); } return $this->iconsList; }
Returns list of icons. @return array file path => name
public function fetchIconsList() { $dir = Yii::getAlias('@hiqdev/paymenticons/assets/png/xs'); $files = scandir($dir); $list = []; foreach ($files as $file) { if ($file[0] === '.') { continue; } $name = pathinfo($file)['filename']; $list["$dir/$file"] = $name; } return $list; }
Scans directory to prepare list of icons. @return array
public function genCss() { $sizes = [ 'xs' => 'height: 38px; width: 60px;', 'sm' => 'height: 75px; width: 120px;', 'md' => 'height: 240px; width: 150px;', 'lg' => 'height: 480px; width: 300px;', ]; $res = '.pi { display: inline-block;height: 38px;width: 60px; }' . PHP_EOL; foreach (array_keys($sizes) as $size) { $res .= ".pi.pi-$size { $sizes[$size] }" . PHP_EOL; } foreach (array_keys($sizes) as $size) { foreach ($this->getIconsList() as $name) { if ($size === 'xs') { $res .= ".pi.pi-$size.pi-$name, .pi.pi-$name { background: url('../png/$size/$name.png') no-repeat right; }" . PHP_EOL; } else { $res .= ".pi.pi-$size.pi-$name { background: url('../png/$size/$name.png') no-repeat right; }" . PHP_EOL; } } $res .= PHP_EOL; } return $res; }
Generates CSS file. @return string
public function connect() { if (! $session = ftp_ssl_connect($this->server, $this->port, $this->timeout)) { throw new ConnectionFailedException('Could not connect to the ssl server'); } $this->setSession($session); }
{@inheritDoc}
public function download($remote, $local, $mode = FTP_BINARY) { if (! ftp_get($this->session, $local, $remote, $mode)) { throw new FileException('File not downloaded'); } return true; }
{@inheritDoc}
public function upload($local, $remote, $mode = FTP_BINARY) { if (! ftp_put($this->session, $remote, $local, $mode)) { throw new FileException('File don\'t uploaded'); } return true; }
{@inheritDoc}
public function wget($httpFile, $remote, $mode = FTP_BINARY) { if (! ini_get('allow_url_fopen')) { throw new \RuntimeException('allow_url_fopen must enabled'); } if (! $handle = fopen($httpFile)) { throw new \RuntimeException('File can not opened'); } if (! ftp_fput($this->session, $remote, $handle, $mode) ) { throw new FileException('File not uploaded to ftp server'); } fclose($handle); return true; }
Upload file to ftp server from http address @link http://php.net/ftp_fput Php manuel @access public @param string $httpFile http file name with address @param string $remote file name to upload ftp server @param string $mode Upload mode FTP_BINARY or FTP_ASCII @return boolean true if success @throws FileException|RuntimeException
public function rename($oldName, $newName) { if (! ssh2_sftp_rename($this->sFtp, $oldName, $newName)) { throw new \RuntimeException('Name can not be changed'); } return true; }
{@inheritDoc} @throws RuntimeException
public function chmod($file, $permission) { if (! ssh2_sftp_chmod($this->sFtp, $file, $permission)) { throw new \RuntimeException('Chmod can not be changed'); } return true; }
{@inheritDoc} @throws RuntimeException
protected function listItem($type, $dir = '/.', $recursive = false, $ignore = array()) { if ($type == 'dir') { $bool = true; } elseif ($type == 'file') { $bool = false; } else { throw new \InvalidArgumentException('$type must "file" or "dir"'); } $parseDir = $this->parseLastDirectory($dir); $sDir = $this->getWrapper($parseDir); $fileList = array_diff(scandir($sDir), array('..', '.')); $fileInfo = array(); foreach ($fileList as $file) { if ($this->ignoreItem($type, $file, $ignore) !== true && is_dir("$sDir/$file") === $bool) { $fileInfo[] = $file; } if ($recursive === true && is_dir("$sDir/$file") === true) { $fileInfo = array_merge($fileInfo, $this->listItem($type, "$dir/$file", $recursive, $ignore)); } } return $fileInfo; }
List of file @link http://php.net/scandir Php manuel @access public @param string $dir ssh directory name @return array file list @throws FileException
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $container->setParameter(self::CONFIG_KEY, $config); // BC $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); $container->findDefinition('cravler_max_mind_geo_ip.service.geo_ip_service')->setArguments(array($config)); try { $loader->load('console.xml'); } catch (\Exception $e) {} }
{@inheritdoc}
public function rm($dir) { $parseDir = $this->parseLastDirectory($dir); if (! ssh2_sftp_rmdir($this->getSFtp(), $parseDir)) { throw new DirectoryException('Directory not deleted'); } return true; }
Remove a directory @link http://php.net/ssh2_sftp_rmdir Php manuel @access public @param string $dir dir name to remove ssh server @return boolean true if success @throws DirectoryException
public function mkdir($dir) { $parseDir = $this->parseLastDirectory($dir); if (! ssh2_sftp_mkdir($this->getSFtp(), $parseDir)) { throw new DirectoryException('Directory can not be created'); } return true; }
{@inheritDoc}
public function get_baselayers(DataContainer $dc) { $id = 0; if ($dc->activeRecord->c4g_map_id != 0) { $id = $dc->activeRecord->c4g_map_id; } else { // take firstMapId, because it will be chosen as DEFAULT value for c4g_map_id $id = $this->firstMapId; } $profile = $this->Database->prepare( "SELECT b.baselayers ". "FROM tl_c4g_maps a, tl_c4g_map_profiles b ". "WHERE a.id = ? and a.profile = b.id") ->execute($id); $ids = deserialize($profile->baselayers,true); if (count($ids)>0) { $baseLayers = $this->Database->prepare("SELECT id,name FROM tl_c4g_map_baselayers WHERE id IN (".implode(',',$ids).") ORDER BY name")->execute(); } else { $baseLayers = $this->Database->prepare("SELECT id,name FROM tl_c4g_map_baselayers ORDER BY name")->execute(); } if ($baseLayers->numRows > 0) { while ( $baseLayers->next () ) { $return [$baseLayers->id] = $baseLayers->name; } } return $return; }
Return all base layers for current Map Profile as array @param object @return array
public function get_maps(DataContainer $dc) { $maps = $this->Database->prepare ( "SELECT * FROM tl_c4g_maps WHERE is_map=1 AND published=1" )->execute (); if ($maps->numRows > 0) { while ( $maps->next () ) { if (!isset($this->firstMapId)) { // save first map id $this->firstMapId = $maps->id; } $return [$maps->id] = $maps->name; } } return $return; }
Return all defined maps @param object @return array