Beispiel #1
0
	/**
	 * This method will be called when the component (or component's parent)
	 * becomes attached to a monitored object. Do not call this method yourself.
	 * @param  Nette\ComponentModel\IComponent
	 * @return void
	 */
	protected function attached($presenter)
	{
		if ($presenter instanceof Presenter) {
			$name = $this->lookupPath('Nette\Application\UI\Presenter');

			if (!isset($this->getElementPrototype()->id)) {
				$this->getElementPrototype()->id = 'frm-' . $name;
			}

			if (iterator_count($this->getControls()) && $this->isSubmitted()) {
				foreach ($this->getControls() as $control) {
					if (!$control->isDisabled()) {
						$control->loadHttpData();
					}
				}
			}

			if (!$this->getAction()) {
				$this->setAction(new Link($presenter, 'this', array()));
				$signal = new Nette\Forms\Controls\HiddenField($name . self::NAME_SEPARATOR . 'submit');
				$signal->setOmitted()->setHtmlId(FALSE);
				$this[Presenter::SIGNAL_KEY] = $signal;
			}
		}
		parent::attached($presenter);
	}
Beispiel #2
0
 /**
  * Recreates the command cursor and counts its results.
  *
  * @see http://php.net/manual/en/countable.count.php
  * @return integer
  */
 public function count()
 {
     $cursor = $this;
     return $this->retry(function () use($cursor) {
         return iterator_count($cursor);
     });
 }
Beispiel #3
0
	/**
	 * This method will be called when the component (or component's parent)
	 * becomes attached to a monitored object. Do not call this method yourself.
	 * @param  IComponent
	 * @return void
	 */
	protected function attached($presenter)
	{
		if ($presenter instanceof NPresenter) {
			$name = $this->lookupPath('NPresenter');

			if (!isset($this->getElementPrototype()->id)) {
				$this->getElementPrototype()->id = 'frm-' . $name;
			}

			$this->setAction(new NLink(
				$presenter,
				$name . self::NAME_SEPARATOR . 'submit!',
				array()
			));

			if (iterator_count($this->getControls()) && $this->isSubmitted()) {
				foreach ($this->getControls() as $control) {
					if (!$control->isDisabled()) {
						$control->loadHttpData();
					}
				}
			}
		}
		parent::attached($presenter);
	}
 /**
  * Envia a notificação para dispositivos Android
  *
  * @param Device[] $devices
  *        	Dispositivos
  * @param Message $message
  *        	Notificação
  * @param NotificationResult $notificationResult
  *        	Resultado do envio da notificação
  * @param PushManager $pushManager
  *        	Gerenciador de push
  */
 public static function send($devices, $message, $notificationResult, $pushManager)
 {
     if (iterator_count($devices->getIterator()) > 0) {
         try {
             $gcmAdapter = new GcmAdapter(array('apiKey' => ANDROID_API_KEY));
             // envia as notificações
             $push = new Push($gcmAdapter, $devices, $message);
             $pushManager->add($push);
             $pushManager->push();
             // obtém a resposta do envio do envio
             $response = $gcmAdapter->getResponse();
             // dispositivo que não receberam as notificações e motivo
             $failureResults = $response->getResult(Response::RESULT_ERROR);
             $failureDevices = AndroidPushController::handleFailureResult($failureResults);
             // dispositivo que tiveram seus identificadores modificados
             $canonicalResults = $response->getResult(Response::RESULT_CANONICAL);
             AndroidPushController::handleCanonicalResult($canonicalResults);
             $notificationResult->addDevicesNotNotified($failureDevices);
         } catch (\Exception $e) {
             global $log;
             $log->Error($e);
             $notificationResult->setAndroidFailed(true);
             $notificationResult->setAndroidFailureReason($e->getMessage());
         }
     }
 }
Beispiel #5
0
function GetPath($path)
{
    $fullPath = system\Helper::arcGetPath(true) . "assets/" . $path . "/";
    $webPath = system\Helper::arcGetPath() . "assets" . $path;
    $files = scandir($fullPath);
    $html = "";
    foreach ($files as $file) {
        if ($file != "." && $file != "..") {
            $html .= "<tr>" . "<td style=\"width: 10px;\"><input type=\"checkbox\" id=\"{$file}\" onchange=\"mark('{$path}/{$file}')\"><label for=\"{$file}\"></label></td>";
            if (is_dir($fullPath . $file)) {
                // folder
                $fi = new FilesystemIterator($fullPath . $file, FilesystemIterator::SKIP_DOTS);
                $html .= "<td><i class=\"fa fa-folder-o\"></i> <a class=\"clickable\" onclick=\"getFolderPath('{$path}/{$file}')\">{$file}</a></td>" . "<td style=\"width: 10px;\">folder</td>" . "<td style=\"width: 10px;\">-</td>" . "<td style=\"width: 100px;\">" . iterator_count($fi) . ngettext(" item", " items", iterator_count($fi)) . "</td>" . "<td style=\"width: 100px;\">" . date("d M Y", filectime($fullPath . $file)) . "</td>";
            } else {
                // get file type
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $filetype = finfo_file($finfo, $fullPath . $file);
                finfo_close($finfo);
                // file
                $html .= "<td><i class=\"" . GetFileTypeIcon($filetype) . "\"></i> <a class=\"clickable\" onclick=\"viewFile('{$webPath}/{$file}', '{$filetype}', '" . FileSizeConvert(filesize($fullPath . $file)) . "', '" . date("d M Y", filectime($fullPath . $file)) . "')\">{$file}<a/></td>" . "<td style=\"width: 10px;\">{$filetype}</td>" . "<td style=\"width: 10px;\"><a alt=\"Copy link to clipboard\" class=\"clickable\" onclick=\"copyToClipboard('{$webPath}/{$file}')\"><i class=\"fa fa-link\"></i></a></td>" . "<td style=\"width: 100px;\">" . FileSizeConvert(filesize($fullPath . $file)) . "</td>" . "<td style=\"width: 100px;\">" . date("d M Y", filectime($fullPath . $file)) . "</td>";
            }
            $html .= "</tr>";
        }
    }
    // no files
    if (count($files) == 2) {
        $html .= "<tr><td colspan=\"4\" class=\"text-center\">Folder is empty.</td></tr>";
    }
    return $html;
}
 /**
  * Flush all processed files to be used for debugging mainly.
  *
  * @return void
  */
 public function flushProcessedFilesCommand()
 {
     foreach ($this->getStorageRepository()->findAll() as $storage) {
         // This only works for local driver
         if ($storage->getDriverType() === 'Local') {
             $this->outputLine();
             $this->outputLine(sprintf('%s (%s)', $storage->getName(), $storage->getUid()));
             $this->outputLine('--------------------------------------------');
             $this->outputLine();
             #$storage->getProcessingFolder()->delete(TRUE); // will not work
             // Well... not really FAL friendly but straightforward for Local drivers.
             $processedDirectoryPath = PATH_site . $storage->getProcessingFolder()->getPublicUrl();
             $fileIterator = new FilesystemIterator($processedDirectoryPath, FilesystemIterator::SKIP_DOTS);
             $numberOfProcessedFiles = iterator_count($fileIterator);
             GeneralUtility::rmdir($processedDirectoryPath, TRUE);
             GeneralUtility::mkdir($processedDirectoryPath);
             // recreate the directory.
             $message = sprintf('Done! Removed %s processed file(s).', $numberOfProcessedFiles);
             $this->outputLine($message);
             // Remove the record as well.
             $record = $this->getDatabaseConnection()->exec_SELECTgetSingleRow('count(*) AS numberOfProcessedFiles', 'sys_file_processedfile', 'storage = ' . $storage->getUid());
             $this->getDatabaseConnection()->exec_DELETEquery('sys_file_processedfile', 'storage = ' . $storage->getUid());
             $message = sprintf('Done! Removed %s records from "sys_file_processedfile".', $record['numberOfProcessedFiles']);
             $this->outputLine($message);
         }
     }
     // Remove possible remaining "sys_file_processedfile"
     $query = 'TRUNCATE sys_file_processedfile';
     $this->getDatabaseConnection()->sql_query($query);
 }
Beispiel #7
0
 public function process()
 {
     $crawler = $this->client->request($this->plan['method'], $this->plan['uri']);
     if (isset($this->plan['selector'])) {
         $selection = $crawler->filter($this->plan['selector']);
     } elseif (isset($this->plan['xpath'])) {
         $selection = $crawler->filterXPath($this->plan['path']);
     }
     if ($this->plan['images']) {
         $images = $selection->filterXPath('//img');
         if (iterator_count($images) > 1) {
             foreach ($images as $image) {
                 $crawler = new Crawler($image);
                 $info = parse_url($this->plan['uri']);
                 $url = $info['scheme'] . '://' . $info['host'] . '/' . $crawler->attr('src');
                 if (strpos($crawler->attr('src'), 'http') === 0) {
                     $url = $info['scheme'] . '://' . $info['host'] . '/' . $this->plan['path'] . $crawler->attr('src');
                 }
                 copy($url, SCRYPHP_STORAGE_PATH_IMG . DIRECTORY_SEPARATOR . substr(strrchr($url, "/"), 1));
             }
         }
     }
     file_put_contents(SCRYPHP_STORAGE_PATH_TXT . DIRECTORY_SEPARATOR . time() . uniqid(time(), true) . '.txt', $selection->text());
     return $selection->text();
 }
Beispiel #8
0
 /**
  * @param array|\Traversable $array
  * @return int
  */
 public static function count($array)
 {
     if (!is_array($array) && !$array instanceof \Traversable) {
         throw new InvalidArgumentException(sprintf('Parameter must be an array or class implements Traversable, %s given.', gettype($array)));
     }
     return $array instanceof \Traversable ? iterator_count($array) : count($array);
 }
 public function parse($output)
 {
     $trlElements = array();
     $fileCount = iterator_count($this->_fileFinder);
     $output->writeln('Twig-Files:');
     $progress = new ProgressBar($output, $fileCount);
     $twig = $this->_createKwfTwigEnvironment();
     foreach ($this->_fileFinder as $file) {
         $nodes = $twig->parse($twig->tokenize(file_get_contents($file->getRealpath()), $file->getRealpath()));
         $trlElementsFromFile = array();
         //Recursively loop through the AST
         foreach ($nodes as $child) {
             if ($child instanceof \Twig_Node) {
                 $trlElementsFromFile = $this->_process($child, $trlElementsFromFile);
             }
         }
         foreach ($trlElementsFromFile as $trlElement) {
             $trlElement['file'] = $file->getRealpath();
             $trlElements[] = $trlElement;
         }
         $progress->advance();
     }
     $progress->finish();
     $output->writeln('');
     return $trlElements;
 }
 public function count()
 {
     if ($this->getInnerIterator() instanceof Countable) {
         return count($this->getInnerIterator());
     }
     return iterator_count($this->getInnerIterator());
 }
 /**
  * @dataProvider provideCases
  */
 function testCases(array $insert, array $params, array $expect)
 {
     $iterator = new ArrayIterator($insert);
     $slice = call_user_func_array([$iterator, 'slice'], $params);
     $this->assertEquals(count($expect), iterator_count($slice));
     $this->assertEquals($expect, $slice->values()->toArray());
 }
Beispiel #12
0
 /**
  * Index the all the files in the directory and sub directories
  *
  * @param string|null $directory
  * @return RecursiveDirectoryIterator
  */
 protected function getIterator($directory = null)
 {
     $directories = $this->config['content_directories'];
     // some flags to filter . and .. and follow symlinks
     $flags = \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS;
     if ($directory) {
         //Iterate only this directory
         return new \RecursiveDirectoryIterator($directory, $flags);
     }
     if ($directories) {
         $directoryIterators = [];
         foreach ($directories as $directory) {
             //Create an array of the paths
             $directoryIterators[] = new \RecursiveDirectoryIterator(each($directory)[1], $flags);
         }
         $iterator = new \AppendIterator();
         foreach ($directoryIterators as $directoryIterator) {
             //Append the directory iterator to the iterator
             $iterator->append(new \RecursiveIteratorIterator($directoryIterator));
         }
     } else {
         throw new Exception("Unable to read the content path, check the configuration file.");
     }
     if (iterator_count($iterator) == 0) {
         throw new Exception("The content directory is empty.");
     }
     return $iterator;
 }
Beispiel #13
0
 /**
  * @param strin|null $url
  * @return void
  */
 public function info($url = null)
 {
     $folder = CACHE . 'views' . DS;
     if (!is_dir($folder)) {
         mkdir($folder, 0770, true);
     }
     if (!$url) {
         $fi = new \FilesystemIterator($folder, \FilesystemIterator::SKIP_DOTS);
         $count = iterator_count($fi);
         $this->out($count . ' cache files found.');
         return;
     }
     $cache = new CacheFilter();
     $file = $cache->getFile($url);
     if (!$file) {
         $this->out('No cache file found');
         return;
     }
     $content = file_get_contents($file);
     $cacheInfo = $cache->extractCacheInfo($content);
     $time = $cacheInfo['time'];
     if ($time) {
         $time = date(FORMAT_DB_DATETIME, $time);
     } else {
         $time = '(unlimited)';
     }
     $this->out('Cache File: ' . basename($file));
     $this->out('URL ext: ' . $cacheInfo['ext']);
     $this->out('Cached until: ' . $time);
 }
Beispiel #14
0
 protected function assertContainsType($type, $expectedCount)
 {
     $it = new \CallbackFilterIterator(new \ArrayIterator($this->types), function ($item) use($type) {
         return $item === $type;
     });
     return $this->assertSame($expectedCount, iterator_count($it));
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('Start up application with supplied config...');
     $config = $input->getArgument('applicationConfig');
     $path = stream_resolve_include_path($config);
     if (!is_readable($path)) {
         throw new \InvalidArgumentException("Invalid loader path: {$config}");
     }
     // Init the application once using given config
     // This way the late static binding on the AspectKernel
     // will be on the goaop-zf2-module kernel
     \Zend\Mvc\Application::init(include $path);
     if (!class_exists(AspectKernel::class, false)) {
         $message = "Kernel was not initialized yet. Maybe missing module Go\\ZF2\\GoAopModule in config {$path}";
         throw new \InvalidArgumentException($message);
     }
     $kernel = AspectKernel::getInstance();
     $options = $kernel->getOptions();
     if (empty($options['cacheDir'])) {
         throw new \InvalidArgumentException('Cache warmer require the `cacheDir` options to be configured');
     }
     $enumerator = new Enumerator($options['appDir'], $options['includePaths'], $options['excludePaths']);
     $iterator = $enumerator->enumerate();
     $totalFiles = iterator_count($iterator);
     $output->writeln("Total <info>{$totalFiles}</info> files to process.");
     $iterator->rewind();
     set_error_handler(function ($errno, $errstr, $errfile, $errline) {
         throw new \ErrorException($errstr, $errno, 0, $errfile, $errline);
     });
     $index = 0;
     $errors = [];
     foreach ($iterator as $file) {
         if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
             $output->writeln("Processing file <info>{$file->getRealPath()}</info>");
         }
         $isSuccess = null;
         try {
             // This will trigger creation of cache
             file_get_contents(FilterInjectorTransformer::PHP_FILTER_READ . SourceTransformingLoader::FILTER_IDENTIFIER . '/resource=' . $file->getRealPath());
             $isSuccess = true;
         } catch (\Exception $e) {
             $isSuccess = false;
             $errors[$file->getRealPath()] = $e;
         }
         if ($output->getVerbosity() == OutputInterface::VERBOSITY_NORMAL) {
             $output->write($isSuccess ? '.' : '<error>E</error>');
             if (++$index % 50 == 0) {
                 $output->writeln("({$index}/{$totalFiles})");
             }
         }
     }
     restore_error_handler();
     if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
         foreach ($errors as $file => $error) {
             $message = "File {$file} is not processed correctly due to exception: {$error->getMessage()}";
             $output->writeln($message);
         }
     }
     $output->writeln('<info>Done</info>');
 }
Beispiel #16
0
 /**
  * Generate the module
  *
  * @return string
  */
 public function run()
 {
     $arrJobs = array();
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_purge_data');
     $objTemplate->isActive = $this->isActive();
     $objTemplate->message = \Message::generateUnwrapped();
     // Run the jobs
     if (\Input::post('FORM_SUBMIT') == 'tl_purge') {
         $purge = \Input::post('purge');
         if (!empty($purge) && is_array($purge)) {
             foreach ($purge as $group => $jobs) {
                 foreach ($jobs as $job) {
                     list($class, $method) = $GLOBALS['TL_PURGE'][$group][$job]['callback'];
                     $this->import($class);
                     $this->{$class}->{$method}();
                 }
             }
         }
         \Message::addConfirmation($GLOBALS['TL_LANG']['tl_maintenance']['cacheCleared']);
         $this->reload();
     }
     // Tables
     foreach ($GLOBALS['TL_PURGE']['tables'] as $key => $config) {
         $arrJobs[$key] = array('id' => 'purge_' . $key, 'title' => $GLOBALS['TL_LANG']['tl_maintenance_jobs'][$key][0], 'description' => $GLOBALS['TL_LANG']['tl_maintenance_jobs'][$key][1], 'group' => 'tables', 'affected' => '');
         // Get the current table size
         foreach ($config['affected'] as $table) {
             $objCount = $this->Database->execute("SELECT COUNT(*) AS count FROM " . $table);
             $arrJobs[$key]['affected'] .= '<br>' . $table . ': <span>' . sprintf($GLOBALS['TL_LANG']['MSC']['entries'], $objCount->count) . ', ' . $this->getReadableSize($this->Database->getSizeOf($table), 0) . '</span>';
         }
     }
     $strCachePath = str_replace(TL_ROOT . DIRECTORY_SEPARATOR, '', \System::getContainer()->getParameter('kernel.cache_dir'));
     // Folders
     foreach ($GLOBALS['TL_PURGE']['folders'] as $key => $config) {
         $arrJobs[$key] = array('id' => 'purge_' . $key, 'title' => $GLOBALS['TL_LANG']['tl_maintenance_jobs'][$key][0], 'description' => $GLOBALS['TL_LANG']['tl_maintenance_jobs'][$key][1], 'group' => 'folders', 'affected' => '');
         // Get the current folder size
         foreach ($config['affected'] as $folder) {
             $total = 0;
             $folder = sprintf($folder, $strCachePath);
             // Only check existing folders
             if (is_dir(TL_ROOT . '/' . $folder)) {
                 $objFiles = Finder::create()->in(TL_ROOT . '/' . $folder)->files();
                 $total = iterator_count($objFiles);
             }
             $arrJobs[$key]['affected'] .= '<br>' . $folder . ': <span>' . sprintf($GLOBALS['TL_LANG']['MSC']['files'], $total) . '</span>';
         }
     }
     // Custom
     foreach ($GLOBALS['TL_PURGE']['custom'] as $key => $job) {
         $arrJobs[$key] = array('id' => 'purge_' . $key, 'title' => $GLOBALS['TL_LANG']['tl_maintenance_jobs'][$key][0], 'description' => $GLOBALS['TL_LANG']['tl_maintenance_jobs'][$key][1], 'group' => 'custom');
     }
     $objTemplate->jobs = $arrJobs;
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->headline = $GLOBALS['TL_LANG']['tl_maintenance']['clearCache'];
     $objTemplate->job = $GLOBALS['TL_LANG']['tl_maintenance']['job'];
     $objTemplate->description = $GLOBALS['TL_LANG']['tl_maintenance']['description'];
     $objTemplate->submit = \StringUtil::specialchars($GLOBALS['TL_LANG']['tl_maintenance']['clearCache']);
     $objTemplate->help = \Config::get('showHelp') && $GLOBALS['TL_LANG']['tl_maintenance']['cacheTables'][1] != '' ? $GLOBALS['TL_LANG']['tl_maintenance']['cacheTables'][1] : '';
     return $objTemplate->parse();
 }
Beispiel #17
0
 /**
  * {@inheritDoc}
  */
 public function process(Configuration $config)
 {
     $sprite = $config->getImagine()->create(new Box(ceil($config->getWidth() * iterator_count($config->getFinder())), 1), $config->getColor());
     $pointer = 0;
     $styles = '';
     foreach ($config->getFinder() as $file) {
         $image = $config->getImagine()->open($file->getRealPath());
         // resize if image exceeds fixed with
         if (true === $this->getOption('resize') && $image->getSize()->getWidth() > $config->getWidth()) {
             $image->resize(new Box($config->getWidth(), round($image->getSize()->getHeight() / $image->getSize()->getWidth() * $config->getWidth())));
         }
         // adjust height if necessary
         if ($image->getSize()->getHeight() > $sprite->getSize()->getHeight()) {
             // copy&paste into an extended sprite
             $sprite = $config->getImagine()->create(new Box($sprite->getSize()->getWidth(), $image->getSize()->getHeight()), $config->getColor())->paste($sprite, new Point(0, 0));
         }
         // paste image into sprite
         $sprite->paste($image, new Point($pointer, 0));
         // append stylesheet code
         $styles .= $this->parseSelector($config->getSelector(), $file, $pointer);
         // move horizontal cursor
         $pointer += $config->getWidth();
     }
     $this->save($config, $sprite, $styles);
 }
 public function parseCodeDirectory($output)
 {
     $this->_errors = array();
     $trlElements = array();
     $fileCount = iterator_count($this->_fileFinder);
     $output->writeln('PHP-Files:');
     $progress = new ProgressBar($output, $fileCount);
     foreach ($this->_fileFinder as $file) {
         if (in_array($file, $this->_ignoredFiles)) {
             continue;
         }
         $progress->advance();
         $this->_codeContent = $this->_replaceShortOpenTags($file->getContents());
         try {
             foreach ($this->parseContent() as $trlElementOfFile) {
                 $trlElementOfFile['file'] = $file->getRealpath();
                 $trlElements[] = $trlElementOfFile;
             }
         } catch (\PhpParser\Error $e) {
             $this->_errors[] = array('error' => $e, 'file' => $file->getRealPath());
         }
     }
     $progress->finish();
     $output->writeln('');
     return $trlElements;
 }
 public function testHttpDataDownloadUsingManyWorkers()
 {
     $filesystem = new Filesystem();
     $targetDirPath = TEMP_DIR . '/' . uniqid('test_http_download');
     $filesystem->mkdir($targetDirPath);
     $workersManager = new Process('php ' . BIN_DIR . '/spider.php worker:start-many -c 3');
     $workersManager->start();
     $this->assertTrue($workersManager->isRunning(), 'Workers Manager should be working');
     $collector = new Process('php ' . BIN_DIR . '/spider.php collector:start --target-folder=' . $targetDirPath);
     $collector->setIdleTimeout(10);
     // there should be an output/result at least once every 10 seconds
     $collector->start();
     $this->assertTrue($collector->isRunning(), 'Task Results Collector should be working');
     $taskLoader = new Process('php ' . BIN_DIR . '/spider.php tasks:load < ' . FIXTURES_DIR . '/uris.txt');
     $taskLoader->setTimeout(120);
     // 120 seconds is enough to complete the task
     $taskLoader->start();
     $this->assertTrue($taskLoader->isRunning(), 'Task Loader should be working');
     while ($taskLoader->isRunning()) {
         sleep(1);
         // waiting for process to complete
     }
     $taskLoaderOutput = $taskLoader->getOutput() . $taskLoader->getErrorOutput();
     $this->assertContains('Total count of Tasks put in the Queue: 10', $taskLoaderOutput, 'Task Loader should have loaded 10 Tasks');
     $this->assertContains('Waiting for acknowledgement from Task Result Collector', $taskLoaderOutput, 'Task Loader should have been waiting for Task Result Collector acknowledgement');
     $this->assertContains('Informing all workers to stop', $taskLoaderOutput, 'Task Loader should have inform Workers to stop');
     $fi = new \FilesystemIterator($targetDirPath, \FilesystemIterator::SKIP_DOTS);
     $this->assertEquals(10, iterator_count($fi), '10 Task Result Files expected');
 }
 public function setUp()
 {
     $this->eshost = '127.0.0.1:9200';
     $this->dir = __DIR__ . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'tweet_files';
     $fi = new FilesystemIterator($this->dir, FilesystemIterator::SKIP_DOTS);
     $this->fileCount = iterator_count($fi);
 }
Beispiel #21
0
 function count()
 {
     if ($this->iterator instanceof \Countable) {
         return $this->iterator->count();
     }
     return iterator_count($this->iterator);
 }
 /**
  * [util function] counts an array, arrayAccess/traversable or PDOStatement object
  *
  * @param  mixed $value
  *
  * @return int   the count for arrays and objects that implement countable, 1 for other objects that don't, and 0
  *               for empty elements
  */
 public function count($value)
 {
     if (is_array($value) === true || $value instanceof Countable) {
         return count($value);
     } elseif ($value instanceof IteratorAggregate) {
         // Note: getIterator() returns a Traversable, not an Iterator
         // thus rewind() and valid() methods may not be present
         return iterator_count($value->getIterator());
     } elseif ($value instanceof Iterator) {
         if ($value instanceof Generator) {
             return 1;
         }
         return iterator_count($value);
     } elseif ($value instanceof PDOStatement) {
         return $value->rowCount();
     } elseif ($value instanceof Traversable) {
         return iterator_count($value);
     } elseif ($value instanceof ArrayAccess) {
         if ($value->offsetExists(0)) {
             return 1;
         }
     } elseif (is_object($value)) {
         return count($value);
     }
     return 0;
 }
Beispiel #23
0
 public function view($file, $vars = [], $paths = [])
 {
     // loop through vars and
     // print our params
     foreach ($this->_parameters as $key => $value) {
         if (!array_key_exists($key, $vars)) {
             $vars[$key] = $value;
         }
     }
     if (!is_array($paths)) {
         $paths = [];
     }
     // paths to find
     $paths += $this->parent('bolt\\browser')->path('views');
     // find this template
     $find = new Finder();
     $base = pathinfo($file)['dirname'];
     $name = pathinfo($file)['basename'];
     // loop through each path
     foreach ($paths as $path) {
         $files = $find->files()->in(b::path($path, $base))->name($name);
         if (iterator_count($files)) {
             $it = iterator_to_array($files);
             $first = array_shift($it);
             return new view(['file' => $first->getRealPath(), 'vars' => $vars, 'context' => $this, 'helpers' => []]);
         }
     }
     // nope
     return false;
 }
 public function testExtractImageToGivenDir()
 {
     $destinationDir = sys_get_temp_dir() . '/pdftoppm';
     @mkdir($destinationDir);
     $result = $this->pdfToPpm->convertPdf(dirname(__DIR__) . '/Resources/test_1_page.pdf', $destinationDir);
     $this->assertSame(1, iterator_count($result));
 }
Beispiel #25
0
 public function testDirectionDownOtherSeekPosition()
 {
     $lexer = new Lexer(['/', '/', '*']);
     $lexer->seek(1);
     $iterator = new MatchingIterator($lexer, '/\\//', MatchingIterator::DIRECTION_DOWN);
     $this->assertEquals(2, iterator_count($iterator));
 }
 /**
  * Renders form end.
  *
  * @return string
  */
 public static function renderFormEnd(Form $form)
 {
     $s = '';
     if (strcasecmp($form->getMethod(), 'get') === 0) {
         $url = explode('?', $form->getElementPrototype()->action, 2);
         if (isset($url[1])) {
             foreach (preg_split('#[;&]#', $url[1]) as $param) {
                 $parts = explode('=', $param, 2);
                 $name = urldecode($parts[0]);
                 if (!isset($form[$name])) {
                     $s .= Nette\Utils\Html::el('input', array('type' => 'hidden', 'name' => $name, 'value' => urldecode($parts[1])));
                 }
             }
         }
     }
     foreach ($form->getComponents(true, 'Nette\\Forms\\Controls\\HiddenField') as $control) {
         if (!$control->getOption('rendered')) {
             $s .= $control->getControl();
         }
     }
     if (iterator_count($form->getComponents(true, 'Nette\\Forms\\Controls\\TextInput')) < 2) {
         $s .= '<!--[if IE]><input type=IEbug disabled style="display:none"><![endif]-->';
     }
     echo ($s ? "<div>{$s}</div>\n" : '') . $form->getElementPrototype()->endTag() . "\n";
 }
Beispiel #27
0
 protected function matches($actual)
 {
     if ($this->analyzer->isInteger($this->expected) === false) {
         throw new \PHPUnit_Framework_Exception('Expected value of ' . __CLASS__ . ' must be an integer');
     }
     switch (true) {
         case $this->analyzer->isArray($actual):
             $asserter = new asserters\phpArray(null, $this->analyzer);
             $asserter->setWith($actual)->hasSize($this->expected);
             break;
         case $actual instanceof \countable:
             $asserter = new asserters\sizeOf(null, $this->analyzer);
             $asserter->setWith($actual)->isEqualTo($this->expected);
             break;
         case $actual instanceof \iteratorAggregate:
             $asserter = new asserters\integer(null, $this->analyzer);
             $asserter->setWith(iterator_count($actual->getIterator()))->isEqualTo($this->expected);
             break;
         case $actual instanceof \traversable:
         case $actual instanceof \iterator:
             $asserter = new asserters\integer(null, $this->analyzer);
             $asserter->setWith(iterator_count($actual))->isEqualTo($this->expected);
             break;
         default:
             throw new \PHPUnit_Framework_Exception('Actual value of ' . __CLASS__ . ' must be an array, a countable object or a traversable object');
     }
 }
Beispiel #28
0
function checkTvImages($pdo, $tvrage)
{
    $text = new Text();
    $images = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tvrage->imgSavePath), RecursiveIteratorIterator::SELF_FIRST);
    if ($images instanceof \Traversable) {
        $imgCount = iterator_count($images);
        echo PHP_EOL . $pdo->log->header("Matching " . number_format($imgCount) . " files to their RageIDs and setting hascover.") . PHP_EOL;
        $checkCnt = $notReqdCnt = $badRageCnt = 0;
        foreach ($images as $file) {
            $rightCut = $text->cutStringUsingLast('/', $file, "right", false);
            $leftCut = $text->cutStringUsingLast('.', $rightCut, "left", false);
            $check = $pdo->queryOneRow(sprintf("SELECT id, hascover\n\t\t\t\t\t\t\t\t\tFROM tvrage_titles\n\t\t\t\t\t\t\t\t\tWHERE rageid = %d", $leftCut));
            if ($check) {
                if ($check['hascover'] == 0) {
                    $pdo->queryExec(sprintf("UPDATE tvrage_titles\n\t\t\t\t\t\t\t\t\t\tSET hascover = 1\n\t\t\t\t\t\t\t\t\t\tWHERE id = %d", $check['id']));
                    $checkCnt++;
                } else {
                    $notReqdCnt++;
                }
            } else {
                $missingRageCnt++;
            }
        }
    }
    echo PHP_EOL . $pdo->log->primary("Updated " . number_format($checkCnt) . " RageIDs. " . number_format($notReqdCnt) . " were already set and " . number_format($missingRageCnt) . " images did not have matching RageIDs in the database.") . PHP_EOL;
}
 /**
  * {@inheritDoc}
  */
 public function countMessages($queueName)
 {
     $iterator = new \RecursiveDirectoryIterator($this->getQueueDirectory($queueName), \FilesystemIterator::SKIP_DOTS);
     $iterator = new \RecursiveIteratorIterator($iterator);
     $iterator = new \RegexIterator($iterator, '#\\.job$#');
     return iterator_count($iterator);
 }
Beispiel #30
0
 /**
  * Create a FileManagerItem given a path. This function can be overriden to customize the displayed information
  * @return FileManagerItem
  */
 protected function _populate_file_item($path, $folder)
 {
     $item = new FileManagerItem();
     $item->path = $path;
     $item->folder = $folder;
     $item->name = basename($path);
     $item->is_folder = is_dir($path);
     if ($item->is_folder) {
         if (!$this->manager->allow_folders) {
             return false;
         }
         $item->info = str_replace('%', max(0, iterator_count(new DirectoryIterator($path)) - 2), $this->manager->strings['number_files']);
     } else {
         $item->size = filesize($path);
         $item->info = jQueryFM_Helper::format_size($item->size);
         //Extract preview
         if ($this->manager->image_preview_limit < 0 || $item->size < $this->manager->image_preview_limit) {
             $extension = strtolower(pathinfo($item->name, PATHINFO_EXTENSION));
             if (in_array($extension, array('jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'))) {
                 //Inline icon (all images in one request, but disable cache)
                 //$item->icon = "data:image/$extension;base64," . base64_encode(file_get_contents($item->path));
                 $item->icon = $this->manager->ajax_endpoint . (strpos($this->manager->ajax_endpoint, '?') !== false ? '&' : '?') . http_build_query(array('action' => 'show', 'file' => $item->name, 'folder' => $item->folder));
             }
         }
     }
     return $item;
 }