View file upload/src/addons/AddonsLab/Core/Service/OptionBuilder.php

File size: 2.76Kb
<?php
/** 
This software is furnished under a license and may be used and copied
only  in  accordance  with  the  terms  of such  license and with the
inclusion of the above copyright notice.  This software  or any other
copies thereof may not be provided or otherwise made available to any
other person.  No title to and  ownership of the  software is  hereby
transferred.                                                         
                                                                     
You may not reverse  engineer, decompile, defeat  license  encryption
mechanisms, or  disassemble this software product or software product
license.  AddonsLab may terminate this license if you don't comply with
any of these terms and conditions.  In such event,  licensee  agrees 
to return licensor  or destroy  all copies of software  upon termination 
of the license.
*/

namespace AddonsLab\Core\Service;

class OptionBuilder
{
    /**
     * @param $flatArray array The array in key=>label format to convert
     * @param $selectedValue string|array if array, allow multiple selected items
     * @return array
     */
    public function convertToOptions($flatArray, $selectedValue)
    {
        $optionsArray = array();

        foreach ($flatArray AS $optionValue => $optionLabel) {
            $selected = (!is_array($selectedValue) && $optionValue==$selectedValue OR is_array($selectedValue) && in_array($optionValue, $selectedValue));

            $optionsArray[$optionValue] = array(
                'value' => $optionValue,
                'label' => $optionLabel,
                'selected' => $selected,
                'depth' => 0,
            );
        }

        return $optionsArray;
    }
    
    public function getCommaSeparatedIdList($optionValue)
    {
        $optionValue=explode(',', $optionValue);
        $optionValue=array_map('intval', $optionValue);
        $optionValue=array_diff($optionValue, array(0));
        
        return $optionValue;
    }

    /**
     * @param string $option
     * @param string $subSeparator
     * @return array
     * Parses a multiline option into an array. If sub-separator is specified, a multi-dimensional array is returned by splitting each line by sub-separator
     */
    public function getMultilineAsArray($option, $subSeparator='')
    {
        $parsedOption=array();
        
        foreach (explode("\n", $option) AS $optionLine) {
            $optionLine=trim($optionLine);
            if(!$optionLine) {
                continue;
            }
            
            if($subSeparator) {
                $optionLine=explode($subSeparator, $optionLine);
                $optionLine=array_map('trim', $optionLine);
            }
            
            $parsedOption[]=$optionLine;
        }
        
        return $parsedOption;
    }
}