A non well formed numeric value encountered Laravel - laravel

I am facing an error in laravel 5.2
ErrorException in Helpers.php line 616:
A non well formed numeric value encountered (View: C:\laragon\www\trunqd-dev\resources\views\post\postCard.blade.php) (View: C:\laragon\www\trunqd-dev\resources\views\post\postCard.blade.php) (View: C:\laragon\www\trunqd-dev\resources\views\post\postCard.blade.php) (View: C:\laragon\www\trunqd-dev\resources\views\post\postCard.blade.php)
my helpers.php
/**
* Store a newly created resource in storage.
*
* #param $width
* #param $height
* #param get Image ratio
* #return Response
*/
function imageRatio($width, $height, $flag = 0, $fixWidth = 218)
{
$n_width = $width > $fixWidth ? $fixWidth : $width;
if(!empty($height) && !empty($width)){
$n_height = floor(($height/$width)*$n_width);
if ($flag == 2) {
$n_height = floor($n_width * 9) / 16;
}
}else{
$n_height = 160;
}
if($flag == 1){
return array('width' => $n_width, 'height' => $n_height);
}
return "width:" . $n_width . "px;height:" . $n_height . "px;";
}
I am using php 7.0. Please assist I don't know why I am facing this error.

Related

pass an index to the method reduce() laravel

I have this function created to show a piechart but I need each element to show a different color. For this I have created an array with all the colors and I need in each iteration of the reduce() method to have an index to access the colors[i]. I have tried this way and it does not work. Any suggestion?
$i = 0;
$pieChartModel = $options->groupBy('survey_options_id')
->reduce(function (PieChartModel $pieChartModel, $data) use ($i) {
$type = $data->first()->survey_options_id;
$value = $data->sum('value');
// $color = "#" . substr(md5(rand()), 0, 6);
$NameOption = Survey_options::where('id', $type)->pluck('name');
return $pieChartModel->addSlice($NameOption, $value, $this->colors[$i]->hexa);
$i++;
}, (new PieChartModel())->setAnimated($this->firstRun)->setDataLabelsEnabled(true));
A problem I'm seeing in your code is how you're incrementing $i AFTER a return statement.
After taking a look at the source code for the reduce() function
/**
* Reduce the collection to a single value.
*
* #param callable $callback
* #param mixed $initial
* #return mixed
*/
public function reduce(callable $callback, $initial = null)
{
$result = $initial;
foreach ($this as $key => $value) {
$result = $callback($result, $value, $key);
}
return $result;
}
You should be able to use the key (or index) in the callback.
->reduce(function ($carry, $item, $key) { ... }, $initial)
->reduce(function (PieChartModel $pieChartModel, $data, $i) {
...
}, (new PieChartModel())->setAnimated($this->firstRun)->setDataLabelsEnabled(true))

How to use pagination in collection fetched by sortBy and where operators?

I need pagination for my collection in which I have to apply lots of filters. But I'm unable to achieve this. I'm new to laravel so please show me the right way.
My controller:
public function index(Request $request)
{
$view = $request['view'] ? $request['view'] :'grid';
$purpose = $request['purpose'] ? $request['purpose'] : 'rent';
$sort = $request['sort'] ? $request['sort'] : 'asc';
$properties = $properties->where('purpose' , $purpose);
if($sort == 'asc');
$properties = $properties->sortBy('price');
else
$properties = $properties->sortByDesc('price');
$properties = $properties->paginate(5);
return view('frontend.properties.index', [ 'view'=>$view , 'properties' => $properties , 'request'=> $request->all() ]);
}
I have had this issue and in order to solve that, I have created a trait called PaginateCollection:
/*
* Paginate the Laravel Collection before and/or after filtering.
*
*/
trait PaginateCollection
{
/**
* Paginate the collection.
*
* #param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Collection $collection
* #param integer $perPage
* #param integer $currentPage
* #return \Illuminate\Pagination\LengthAwarePaginator
*/
public function paginate($collection, $perPage = 10, $currentPage = 1)
{
$offSet = ($currentPage * $perPage) - $perPage;
$otherParams = [
'path' => request()->url(),
'query' => request()->query()
];
return new LengthAwarePaginator(
$collection->forPage(Paginator::resolveCurrentPage() , $perPage),
$collection->count(),
$perPage,
Paginator::resolveCurrentPage(),
$otherParams
);
}
}
Perhaps, this should help you out.

How to make pagination after merge two collections?

I use the standart method for pagination:
$ann = Ann::get()->orderBy('id', 'desc')->paginate($limit);
After I do merge $ann with another collection:
$ann = $ann->merge($ann_subscribed);
$ann = $ann->all();
In result I get $ann = $ann->all(); without pagination
1- add this to boot function in \app\Providers\AppServiceProvider
/**
* Paginate a standard Laravel Collection.
*
* #param int $perPage
* #param int $total
* #param int $page
* #param string $pageName
* #return array
*/
Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
2-From hereafter for all collection you can paginate like this
$ann = Ann::orderByRaw('id','DESC')->get();
$ann_merged = $ann->merge($ann_subscribed);
$ann_merged ->paginate(5);

typo3 viewhelper is only called once

I have made an own viewhelper for getting external images (thanks to robert pflamm see Typo3 fluid image from external resource). if i use only ImageViewHelper everything is working finde.
But if i use \TYPO3\CMS\Fluid\ViewHelpers\Uri\ImageViewHelper the image is only rendered once. Same problem as here TYPO3 ver. 7.6.2 - Condition ViewHelpers evaluated only once. but i do not know how to solve it
Can anyone please help?
martin
namespace Mwxxx\Mwxxx\ViewHelpers;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Fluid\ViewHelpers\Uri\ImageViewHelper;
use TYPO3\CMS\Core\Resource\FileInterface;
use TYPO3\CMS\Extbase\Domain\Model\AbstractFileFolder;
class ExternalImageViewHelper extends \TYPO3\CMS\Fluid\ViewHelpers\Uri\ImageViewHelper
{
const UPLOAD_DIRECTORY = 'upload';
const TEMP_PREFIX = 'Mwxx';
/**
* ResourceFactory
*
* #var \TYPO3\CMS\Core\Resource\ResourceFactory
* #inject
*/
protected $resourceFactory = null;
/**
* Resizes a given image (if required) and renders the respective img tag
*
* #see https://docs.typo3.org/typo3cms/TyposcriptReference/ContentObjects/Image/
*
* #param string $src a path to a file, a combined FAL identifier or an uid (integer). If $treatIdAsReference is set, the integer is considered the uid of the sys_file_reference record. If you already got a FAL object, consider using the $image parameter instead
* #param string $width width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.
* #param string $height height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.
* #param integer $minWidth minimum width of the image
* #param integer $minHeight minimum height of the image
* #param integer $maxWidth maximum width of the image
* #param integer $maxHeight maximum height of the image
* #param boolean $treatIdAsReference given src argument is a sys_file_reference record
* #param FileInterface|AbstractFileFolder $image a FAL object
*
* #return string
* #throws \Exception
* #throws \TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException
* #throws \TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException
* #throws \TYPO3\CMS\Fluid\Core\ViewHelper\Exception
*/
public function render($src = null, $image = null, $width = null, $height = null, $minWidth = null, $minHeight = null, $maxWidth = null, $maxHeight = null, $treatIdAsReference = false)
{
if (filter_var($src, FILTER_VALIDATE_URL)) {
$storage = $this->resourceFactory->getDefaultStorage();
if (!$storage->hasFolder(self::UPLOAD_DIRECTORY)) {
$storage->createFolder(self::UPLOAD_DIRECTORY);
}
if (file_exists('fileadmin/upload/'.basename(basename($src)))) {
#echo "Die Datei $filename existiert";
$src = 'fileadmin/upload/'.basename(basename($src));
}
else {
$externalFile = GeneralUtility::getUrl($src);
if ($externalFile) {
$tempFileName = tempnam(sys_get_temp_dir(), self::TEMP_PREFIX);
$handle = fopen($tempFileName, "w");
fwrite($handle, $externalFile);
fclose($handle);
$uploadFolder = $storage->getFolder(self::UPLOAD_DIRECTORY);
#echo "Die Datei $filename existiert nicht";
$file = $uploadFolder->addFile($tempFileName, basename(basename($src)), 'changeName');
$src = $file->getPublicUrl();
#unlink($tempFileName);
} else {
throw new \Exception(sprintf('External URL % cannot accessed.', $src), 1473233519);
}
}
}
return parent::render($src, $image, $width, $height, $minWidth, $minHeight, $maxWidth, $maxHeight, $treatIdAsReference);
}
}
The viewhelpers are not really a public API which are meant to be extensible by custom ViewHelpers!
The problem you are facing is that after the 1st call, the ViewHelpers are compiled and the method renderStatic is used which you don't override.
The best solution would be that you copy the code of the parent class and only extend from AbstractViewHelper or AbstractTagBasedViewHelper

Typo3 fluid image from external resource

is it possible to resize images in fluid from external resource. I have an extension with datas from SOAP. So image URL looks like http://www.example.com/url/of/image/imagename.jpg.
<f:image src="{data.url.image}" with="300" />
is not working.
Maybe an own ViewHelper which fetch the external image and save it to an temporary folder could help. After this you can modify the image.
Something like this (not tested):
<?php
namespace MyNamespaece\MyExt\ViewHelpers;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Fluid\ViewHelpers\ImageViewHelper;
use TYPO3\CMS\Core\Resource\FileInterface;
use TYPO3\CMS\Extbase\Domain\Model\AbstractFileFolder;
class ExternalImageViewHelper extends ImageViewHelper
{
const UPLOAD_DIRECTORY = 'externalImages';
const TEMP_PREFIX = 'MyExt';
/**
* ResourceFactory
*
* #var \TYPO3\CMS\Core\Resource\ResourceFactory
* #inject
*/
protected $resourceFactory = null;
/**
* Resizes a given image (if required) and renders the respective img tag
*
* #see https://docs.typo3.org/typo3cms/TyposcriptReference/ContentObjects/Image/
*
* #param string $src a path to a file, a combined FAL identifier or an uid (integer). If $treatIdAsReference is set, the integer is considered the uid of the sys_file_reference record. If you already got a FAL object, consider using the $image parameter instead
* #param string $width width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.
* #param string $height height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.
* #param integer $minWidth minimum width of the image
* #param integer $minHeight minimum height of the image
* #param integer $maxWidth maximum width of the image
* #param integer $maxHeight maximum height of the image
* #param boolean $treatIdAsReference given src argument is a sys_file_reference record
* #param FileInterface|AbstractFileFolder $image a FAL object
*
* #return string
* #throws \Exception
* #throws \TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException
* #throws \TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException
* #throws \TYPO3\CMS\Fluid\Core\ViewHelper\Exception
*/
public function render($src = null, $width = null, $height = null, $minWidth = null, $minHeight = null, $maxWidth = null, $maxHeight = null, $treatIdAsReference = false, $image = null)
{
if (filter_var($src, FILTER_VALIDATE_URL)) {
$storage = $this->resourceFactory->getDefaultStorage();
if (!$storage->hasFolder(self::UPLOAD_DIRECTORY)) {
$storage->createFolder(self::UPLOAD_DIRECTORY);
}
$externalFile = GeneralUtility::getUrl($src);
if ($externalFile) {
$tempFileName = tempnam(sys_get_temp_dir(), self::TEMP_PREFIX);
$handle = fopen($tempFileName, "w");
fwrite($handle, $externalFile);
fclose($handle);
$uploadFolder = $storage->getFolder(self::UPLOAD_DIRECTORY);
$file = $uploadFolder->addFile($tempFileName, basename(basename($src)), 'changeName');
$src = $file->getPublicUrl();
unlink($tempFileName);
} else {
throw new \Exception(sprintf('External URL % cannot accessed.', $src), 1473233519);
}
}
return parent::render($src, $width, $height, $minWidth, $minHeight, $maxWidth, $maxHeight, $treatIdAsReference, $image);
}
}
Please Note: This ViewHelper has no check if the image is allready fetched! So an check should be integrated. Otherwise this viewhelper fetch the image at each page refresh!
As mentioned in the comments I want to clarify that this ViewHelper should not be used in any production environment. It should only demonstrate how the way to such an viewhelper could be. Compiled templates are not supported. Also no needed check if the file already exists is implemented. Your hosting environment could be flooded with downloads and can break you file quota!
The short answer is: This is not possible.
The long answer is: Of course it is possible if you fetch the image first. There are various ways to do it:
At runtime as rpflamm suggested by using a ViewHelper
Do it in your controller/service when you fetch the SOAP call. IMO this would be the best way. Persist then the image and use the local path
If the images you fetch are not that big, of course a resizing via CSS is also an option
Working Version with cropping-feature for TYPO3 10.4 LTS:
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*
* Example: <xyz:externalImage filename="OPTINAL_FILENAME" src="EXTERNAL_URL" width="480c" height="270c" title="YOUR TITLE" alt="YOUR ALT" class="YOUR-CLASS" />
*/
namespace YourNamespaece\YourExtension\ViewHelpers;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Service\ImageService;
use TYPO3\CMS\Fluid\Core\Widget\Exception;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper;
class ExternalImageViewHelper extends AbstractTagBasedViewHelper {
/**
* #var string
*/
protected $tagName = 'img';
/**
* #var \TYPO3\CMS\Extbase\Service\ImageService
*/
protected $imageService;
/**
* #param \TYPO3\CMS\Extbase\Service\ImageService $imageService
*/
public function injectImageService(ImageService $imageService)
{
$this->imageService = $imageService;
}
const UPLOAD_DIRECTORY = 'externalImages';
const TEMP_PREFIX = 'diakonie_baukasten';
/**
* ResourceFactory
*
* #var ResourceFactory
* #TYPO3\CMS\Extbase\Annotation\Inject
*/
protected ResourceFactory $resourceFactory;
/**
* Initialize arguments.
*/
public function initializeArguments()
{
parent::initializeArguments();
$this->registerUniversalTagAttributes();
$this->registerTagAttribute('alt', 'string', 'Specifies an alternate text for an image', false);
$this->registerArgument('filename', 'string', 'Override filename for local file.', false, '');
$this->registerArgument('src', 'string', 'a path to a file, a combined FAL identifier or an uid (int). If $treatIdAsReference is set, the integer is considered the uid of the sys_file_reference record. If you already got a FAL object, consider using the $image parameter instead', true, '');
$this->registerArgument('width', 'string', 'width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.');
$this->registerArgument('height', 'string', 'height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.');
$this->registerArgument('minWidth', 'int', 'minimum width of the image');
$this->registerArgument('minHeight', 'int', 'minimum height of the image');
$this->registerArgument('maxWidth', 'int', 'maximum width of the image');
$this->registerArgument('maxHeight', 'int', 'maximum height of the image');
$this->registerArgument('absolute', 'bool', 'Force absolute URL', false, false);
}
/**
* Resizes a given image (if required) and renders the respective img tag
*
* #see https://docs.typo3.org/typo3cms/TyposcriptReference/ContentObjects/Image/
*
* #return string Rendered tag
* #throws \Exception
*/
public function render()
{
$src = (string)$this->arguments['src'];
$filename = (string)$this->arguments['filename'];
if ($src === '') {
throw new Exception('You must either specify a string src', 1382284106);
}
// A URL was given as src, this is kept as is, and we can only scale
if ($src !== '' && preg_match('/^(https?:)?\/\//', $src)) {
if (filter_var($src, FILTER_VALIDATE_URL)) {
$storage = $this->resourceFactory->getDefaultStorage();
if (!$storage->hasFolder(self::UPLOAD_DIRECTORY)) {
$storage->createFolder(self::UPLOAD_DIRECTORY);
}
$externalFile = GeneralUtility::getUrl($src);
if ($externalFile) {
$tempFileName = tempnam(sys_get_temp_dir(), self::TEMP_PREFIX);
$handle = fopen($tempFileName, "w");
fwrite($handle, $externalFile);
fclose($handle);
if ($filename !== '') {
$fileNameNoExtension = preg_replace("/\.[^.]+$/", "", $src);
$fileExtension = str_replace($fileNameNoExtension,"", $src);
$src = $filename.$fileExtension;
}
$uploadFolder = $storage->getFolder(self::UPLOAD_DIRECTORY);
$file = $uploadFolder->addFile($tempFileName, basename(basename($src)), 'replace');
$src = $file->getPublicUrl();
unlink($tempFileName);
$image = $this->imageService->getImage($src, null, false);
$processingInstructions = [
'width' => $this->arguments['width'],
'height' => $this->arguments['height'],
'minWidth' => $this->arguments['minWidth'],
'minHeight' => $this->arguments['minHeight'],
'maxWidth' => $this->arguments['maxWidth'],
'maxHeight' => $this->arguments['maxHeight'],
'crop' => null,
];
$processedImage = $this->imageService->applyProcessingInstructions($image, $processingInstructions);
$imageUri = $this->imageService->getImageUri($processedImage, $this->arguments['absolute']);
$this->tag->addAttribute('src', $imageUri);
$this->tag->addAttribute('width', $processedImage->getProperty('width'));
$this->tag->addAttribute('height', $processedImage->getProperty('height'));
// The alt-attribute is mandatory to have valid html-code, therefore add it even if it is empty
if (empty($this->arguments['alt'])) {
$this->tag->addAttribute('alt', $image->hasProperty('alternative') ? $image->getProperty('alternative') : '');
}
// Add title-attribute from property if not already set and the property is not an empty string
$title = (string)($image->hasProperty('title') ? $image->getProperty('title') : '');
if (empty($this->arguments['title']) && $title !== '') {
$this->tag->addAttribute('title', $title);
}
return $this->tag->render();
} else {
throw new \Exception(sprintf('External URL % cannot accessed.', $src), 1473233519);
}
}
}
}
}

Resources