Implements ordered keyed array of PhpValue with PHP semantics.
Inheritance: PhpHashtable, IPhpConvertible, IPhpArray, IPhpComparable, IPhpEnumerable
Ejemplo n.º 1
0
 /// <summary>
 /// Constructs the object with single runtime field <c>scalar</c>.
 /// </summary>
 /// <param name="scalar">Value of <c>scalar</c> field.</param>
 internal stdClass(PhpValue scalar)
 {
     __peach__runtimeFields = new PhpArray(1)
     {
         { new IntStringKey("scalar"), scalar }
     };
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Calls a function or a method defined by callback with arguments stored in an array.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="function">Target callback.</param>
        /// <param name="args">Arguments. Can be null.</param>
        /// <returns>The returned value.</returns>
        public static PhpValue call_user_func_array(Context ctx, IPhpCallable function, PhpArray args)
        {
            PhpValue[] args_array;

            if (args != null && args.Count != 0)
            {
                args_array = new PhpValue[args.Count];
                args.CopyValuesTo(args_array, 0);
            }
            else
            {
                args_array = Core.Utilities.ArrayUtils.EmptyValues;
            }

            return call_user_func(ctx, function, args_array);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Retrieves defined constants.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="categorize">Returns a multi-dimensional array with categories in the keys of the first dimension and constants and their values in the second dimension. </param>
        /// <returns>Retrives the names and values of all the constants currently defined.</returns>
        public static PhpArray get_defined_constants(Context ctx, bool categorize = false)
        {
            var result = new PhpArray();

            if (categorize)
            {
                throw new NotImplementedException();
            }
            else
            {
                foreach (var c in ctx.GetConstants())
                {
                    result.Add(c.Key, c.Value);
                }
            }

            //
            return result;
        }
Ejemplo n.º 4
0
 public static PhpArray preg_grep(string pattern, PhpArray input, int flags = 0)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 5
0
        internal static PhpArray GetLocalTime(TimeZoneInfo currentTz, System_DateTime utc, bool returnAssociative)
        {
            PhpArray result;

            var local = TimeZoneInfo.ConvertTime(utc, currentTz);

            if (returnAssociative)
            {
                result = new PhpArray(0, 9);
                result["tm_sec"] = PhpValue.Create(local.Second);
                result["tm_min"] = PhpValue.Create(local.Minute);
                result["tm_hour"] = PhpValue.Create(local.Hour);
                result["tm_mday"] = PhpValue.Create(local.Day);
                result["tm_mon"] = PhpValue.Create(local.Month - 1);
                result["tm_year"] = PhpValue.Create(local.Year - 1900);
                result["tm_wday"] = PhpValue.Create((int)local.DayOfWeek);
                result["tm_yday"] = PhpValue.Create(local.DayOfYear - 1);
                result["tm_isdst"] = PhpValue.Create(currentTz.IsDaylightSavingTime(local) ? 1 : 0);
            }
            else
            {
                result = new PhpArray(9, 0);
                result.AddValue(PhpValue.Create(local.Second));
                result.AddValue(PhpValue.Create(local.Minute));
                result.AddValue(PhpValue.Create(local.Hour));
                result.AddValue(PhpValue.Create(local.Day));
                result.AddValue(PhpValue.Create(local.Month - 1));
                result.AddValue(PhpValue.Create(local.Year - 1900));
                result.AddValue(PhpValue.Create((int)local.DayOfWeek));
                result.AddValue(PhpValue.Create(local.DayOfYear - 1));
                result.AddValue(PhpValue.Create(currentTz.IsDaylightSavingTime(local) ? 1 : 0));
            }

            return result;
        }
Ejemplo n.º 6
0
 public static int preg_match_all(Context ctx, string pattern, string subject, out PhpArray matches, int flags = PREG_PATTERN_ORDER, int offset = 0)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 7
0
            public override void Accept(PhpArray obj)
            {
                // array (
                _output.Append(PhpArray.PhpTypeName);
                _output.Append(" (");
                _output.Append(_nl);
                
                _indent++;

                base.Accept(obj);

                _indent--;
                OutputIndent();
                _output.Append(")");
            }
Ejemplo n.º 8
0
        /// <summary>
        /// Returns an associative array containing the date information.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="utc">UTC date time.</param>
        /// <returns>Associative array with date information.</returns>
        static PhpArray GetDate(Context ctx, System_DateTime utc)
        {
            PhpArray result = new PhpArray(1, 10);

            var zone = PhpTimeZone.GetCurrentTimeZone(ctx);
            var local = TimeZoneInfo.ConvertTime(utc, zone);

            result.Add("seconds", local.Second);
            result.Add("minutes", local.Minute);
            result.Add("hours", local.Hour);
            result.Add("mday", local.Day);
            result.Add("wday", (int)local.DayOfWeek);
            result.Add("mon", local.Month);
            result.Add("year", local.Year);
            result.Add("yday", local.DayOfYear - 1); // PHP: zero based day count
            result.Add("weekday", local.DayOfWeek.ToString());
            result.Add("month", local.ToString("MMMM", DateTimeFormatInfo.InvariantInfo));
            result.Add(0, DateTimeUtils.UtcToUnixTimeStamp(utc));

            return result;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Pads array to the specified length with a value.
        /// If the length is negative adds |length| elements at beginning otherwise adds elements at the end.
        /// Values with integer keys that are contained in the source array are inserted to the resulting one with new 
        /// integer keys counted from zero (or from |length| if length negative).
        /// </summary>
        /// <param name="array">The source array.</param>
        /// <param name="length">The length of the resulting array.</param>
        /// <param name="value">The value to add in array.</param>
        /// <returns>Padded array.</returns>
        /// <exception cref="PhpException">The <paramref name="array"/> argument is a <B>null</B> reference.</exception>
        public static PhpArray array_pad(PhpArray array, int length, PhpValue value)
        {
            if (array == null)
            {
                // PhpException.ArgumentNull("array");
                // return null;
                throw new ArgumentNullException();
            }

            // number of items to add:
            int remains = Math.Abs(length) - array.Count;

            // returns unchanged array (or its deep copy if called from PHP):
            if (remains <= 0) return array;

            PhpArray result = new PhpArray(array.Count + remains);

            // prepends items:
            if (length < 0)
            {
                while (remains-- > 0) result.Add(value);
            }

            // inserts items from source array
            // if a key is a string inserts it unchanged otherwise inserts value with max. integer key:  
            var iterator = array.GetFastEnumerator();
            while (iterator.MoveNext())
            {
                var key = iterator.CurrentKey;
                if (key.IsString)
                    result.Add(key, iterator.CurrentValue);
                else
                    result.Add(iterator.CurrentValue);
            }

            // appends items:
            if (length > 0)
            {
                while (remains-- > 0) result.Add(value);
            }

            // the result is inplace deeply copied on return to PHP code:
            //result.InplaceCopyOnReturn = true;
            return result;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Creates an array containing range of doubles from the [low;high] interval with arbitrary step.
        /// </summary>
        /// <param name="low">Lower bound of the interval.</param>
        /// <param name="high">Upper bound of the interval.</param>
        /// <param name="step">The step. An absolute value is taken if step is less than zero.</param>
        /// <returns>The array.</returns>
        /// <exception cref="PhpException">Thrown if the <paramref name="step"/> argument is zero.</exception>
        private static PhpArray RangeOfDoubles(double low, double high, double step)
        {
            if (step == 0)
            {
                //PhpException.InvalidArgument("step", LibResources.GetString("arg:zero"));
                //return null;
                throw new ArgumentException();
            }

            if (step < 0) step = -step;

            PhpArray result = new PhpArray(System.Convert.ToInt32(Math.Abs(high - low) / step) + 1);

            if (high >= low)
            {
                for (int i = 0; low <= high; i++, low += step) result.Add(i, low);
            }
            else
            {
                for (int i = 0; low >= high; i++, low -= step) result.Add(i, low);
            }

            return result;
        }
Ejemplo n.º 11
0
        /// <summary>
		/// Create a new context resource from an array of wrapper options.
		/// </summary>
		/// <param name="data">A 2-dimensional array of wrapper options</param>
        public StreamContext(PhpArray data)
            : this(data, true) { }
Ejemplo n.º 12
0
        /// <summary>
		/// Creates a new array filled with a specified value.
		/// </summary>
		/// <param name="startIndex">The value of the key of the first item in the array.</param>
		/// <param name="count">The number of items in the array.</param>
		/// <param name="value">The value copied to all items in the array.</param>
		/// <returns>The array.</returns>
		/// <exception cref="PhpException">Thrown if <paramref name="count"/> is not positive.</exception>
		public static PhpArray array_fill(int startIndex, int count, PhpValue value)
        {
            if (count <= 0)
            {
                // TODO: PhpException.InvalidArgument("count", LibResources.GetString("arg:negative_or_zero"));
                return null;
            }

            PhpArray result = new PhpArray(count, 0);
            int last = startIndex + count;
            for (int i = startIndex; i < last; i++)
                result.Add(i, value);

            // makes deep copies of all added items:
            //result.InplaceCopyOnReturn = true;
            return result;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Compares two instances of <see cref="PhpArray"/>.
        /// </summary>
        /// <param name="x">First operand. Cannot be <c>null</c>.</param>
        /// <param name="y">Second operand. Cannot be <c>null</c>.</param>
        /// <param name="comparer">The comparer.</param>
        /// <param name="incomparable">Whether arrays are incomparable
        /// (no difference is found before both arrays enters an infinite recursion).
        /// Returns zero then.</param>
        public static int CompareArrays(PhpArray x, PhpArray y, IComparer <PhpValue> comparer, out bool incomparable)
        {
            Debug.Assert(x != null && y != null);

            incomparable = false;

            // if both operands point to the same internal dictionary:
            if (object.ReferenceEquals(x.table, y.table))
            {
                return(0);
            }

            //
            PhpArray array_x, array_y;
            PhpArray sorted_x, sorted_y;

            // if numbers of elements differs:
            int result = x.Count - y.Count;

            if (result != 0)
            {
                return(result);
            }

            // comparing with the same instance:
            if (x == y)
            {
                return(0);
            }

            // marks arrays as visited (will be always restored to false value before return):
            x.Visited = true;
            y.Visited = true;

            // it will be more effective to implement OrderedHashtable.ToOrderedList method and use it here (in future version):
            sorted_x = x.DeepCopy();
            sorted_x.Sort(KeyComparer.ArrayKeys);
            sorted_y = y.DeepCopy();
            sorted_y.Sort(KeyComparer.ArrayKeys);

            var iter_x = sorted_x.GetFastEnumerator();
            var iter_y = sorted_y.GetFastEnumerator();

            result = 0;

            try
            {
                // compares corresponding elements (keys first values then):
                while (iter_x.MoveNext())
                {
                    iter_y.MoveNext();

                    // compares keys:
                    result = iter_x.CurrentKey.CompareTo(iter_y.CurrentKey);
                    if (result != 0)
                    {
                        break;
                    }

                    // dereferences childs if they are references:
                    var child_x = iter_x.CurrentValue.GetValue();
                    var child_y = iter_y.CurrentValue.GetValue();

                    // compares values:
                    if ((array_x = child_x.ArrayOrNull()) != null)
                    {
                        if ((array_y = child_y.ArrayOrNull()) != null)
                        {
                            // at least one child has not been visited yet => continue with recursion:
                            if (!array_x.Visited || !array_y.Visited)
                            {
                                result = CompareArrays(array_x, array_y, comparer, out incomparable);
                            }
                            else
                            {
                                incomparable = true;
                            }

                            // infinity recursion has been detected:
                            if (incomparable)
                            {
                                break;
                            }
                        }
                        else
                        {
                            // compares an array with a non-array:
                            array_x.Compare(child_y, comparer);
                        }
                    }
                    else
                    {
                        // compares unknown item with a non-array:
                        result = -comparer.Compare(child_y, child_x);
                    }

                    if (result != 0)
                    {
                        break;
                    }
                } // while
            }
            finally
            {
                x.Visited = false;
                y.Visited = false;
            }
            return(result);
        }
 public static PhpArray ToArray(bool value) => PhpArray.New(value);
 public static PhpArray ToArray(double value) => PhpArray.New(value);
 public static PhpArray ToArray(long value) => PhpArray.New(value);
Ejemplo n.º 17
0
        /// <summary>
        /// Compares two instances of <see cref="PhpArray"/> for strict equality.
        /// </summary>
        /// <param name="x">First operand. Cannot be <c>null</c>.</param>
        /// <param name="y">Second operand. Cannot be <c>null</c>.</param>
        /// <param name="incomparable">Whether arrays are incomparable
        /// (no difference is found before both arrays enters an infinite recursion).
        /// Returns <B>true</B> then.</param>
        static bool StrictCompareArrays(PhpArray x, PhpArray y, out bool incomparable)
        {
            Debug.Assert(x != null && y != null);

            incomparable = false;

            // if both operands point to the same internal dictionary:
            if (object.ReferenceEquals(x.table, y.table))
            {
                return(true);
            }

            // if numbers of elements differs:
            if (x.Count != y.Count)
            {
                return(false);
            }

            // comparing with the same instance:
            if (x == y)
            {
                return(true);
            }

            var iter_x = x.GetFastEnumerator();
            var iter_y = y.GetFastEnumerator();

            PhpArray array_x, array_y;

            // marks arrays as visited (will be always restored to false value before return):
            x.Visited = true;
            y.Visited = true;

            bool result = true;

            try
            {
                // compares corresponding elements (keys first values then):
                while (result && iter_x.MoveNext())
                {
                    iter_y.MoveNext();

                    // compares keys:
                    if (!iter_x.Current.Key.Equals(iter_y.Current.Key))
                    {
                        result = false;
                        break;
                    }

                    var child_x = iter_x.CurrentValue;
                    var child_y = iter_y.CurrentValue;

                    // compares values:
                    if ((array_x = child_x.ArrayOrNull()) != null)
                    {
                        if ((array_y = child_y.ArrayOrNull()) != null)
                        {
                            // at least one child has not been visited yet => continue with recursion:
                            if (!array_x.Visited || !array_y.Visited)
                            {
                                result = StrictCompareArrays(array_x, array_y, out incomparable);
                            }
                            else
                            {
                                incomparable = true;
                                break;
                            }
                        }
                        else
                        {
                            // an array with a non-array comparison:
                            result = false;
                        }
                    }
                    else
                    {
                        // compares unknown item with a non-array:
                        result = child_x.GetValue().StrictEquals(child_y.GetValue());
                    }
                } // while
            }
            finally
            {
                x.Visited = false;
                y.Visited = false;
            }
            return(result);
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Makes new array containing union of two arrays.
 /// </summary>
 public static PhpArray Union(PhpArray x, PhpArray y) => (PhpArray)x.DeepCopy().Unite(y);
Ejemplo n.º 19
0
 /// <summary>
 /// Removes a slice of an array.
 /// </summary>
 /// <param name="array">The array which slice to remove.</param>
 /// <param name="offset">The relativized offset of a first item of the slice.</param>
 /// <param name="length">The relativized length of the slice.</param>
 /// <remarks>
 /// <para><paramref name="length"/> items are removed from <paramref name="array"/> 
 /// starting with the <paramref name="offset"/>-th one.</para>
 /// </remarks>
 /// <para>See <see cref="PhpMath.AbsolutizeRange"/> for details about <paramref name="offset"/>.</para>
 public static PhpArray array_splice(PhpArray array, int offset, int length = int.MaxValue)
 {
     // Splice would be equivalent to SpliceDc if no replacement is specified (=> no SpliceDc):
     return array_splice(array, offset, length, PhpValue.Null);
 }
Ejemplo n.º 20
0
        public static PhpArray array_fill_keys(PhpArray keys, PhpValue value)
        {
            if (keys == null)
            {
                // PhpException.ArgumentNull("keys");
                // return null;
                throw new ArgumentNullException();
            }

            var result = new PhpArray(keys.Count);
            var iterator = keys.GetFastEnumerator();
            while (iterator.MoveNext())
            {
                IntStringKey key;
                if (Core.Convert.TryToIntStringKey(iterator.CurrentValue, out key) && !result.ContainsKey(key))
                {
                    result[key] = value;
                }
            }

            // makes deep copies of all added items:
            //result.InplaceCopyOnReturn = true;
            return result;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Replaces a slice of an array with specified item(s).
        /// </summary>
        /// <remarks>
        /// <para>The same as <see cref="Splice(PhpArray,int,int,object)"/> except for that
        /// replacement items are deeply copied to the <paramref name="array"/>.</para>
        /// </remarks>
        public static PhpArray array_splice(PhpArray array, int offset, int length, PhpValue replacement)
        {
            if (array == null)
            {
                //PhpException.Throw(
                //    PhpError.Warning,
                //    string.Format(Strings.unexpected_arg_given, "array", PhpArray.PhpTypeName, PhpVariable.TypeNameNull));
                //return null;
                throw new ArgumentNullException();
            }

            return SpliceInternal(array, offset, length, replacement, true);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Creates an array containing range of long integers from the [low;high] interval with arbitrary step.
        /// </summary>
        /// <param name="low">Lower bound of the interval.</param>
        /// <param name="high">Upper bound of the interval.</param>
        /// <param name="step">The step. An absolute value is taken if step is zero.</param>
        /// <returns>The array.</returns>
        private static PhpArray RangeOfLongInts(long low, long high, long step)
        {
            if (step == 0)
            {
                //PhpException.InvalidArgument("step", LibResources.GetString("arg:zero"));
                //return null;
                throw new ArgumentException();
            }

            if (step < 0) step = -step;

            PhpArray result = new PhpArray(unchecked((int)(Math.Abs(high - low) / step + 1)));

            if (high >= low)
            {
                for (int i = 0; low <= high; i++, low += step) result.Add(i, low);
            }
            else
            {
                for (int i = 0; low >= high; i++, low -= step) result.Add(i, low);
            }

            return result;
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Implementation of <see cref="array_splice(PhpArray,int,int,object)"/> and <see cref="array_splice(PhpArray,int,int,object)"/>.
        /// </summary>
        /// <remarks>Whether to make a deep-copy of items in the replacement.</remarks>
        internal static PhpArray SpliceInternal(PhpArray array, int offset, int length, PhpValue replacement, bool deepCopy)
        {
            Debug.Assert(array != null);
            int count = array.Count;

            // converts offset and length to interval [first,last]:
            PhpMath.AbsolutizeRange(ref offset, ref length, count);

            PhpArray result = new PhpArray(length);

            // replacement is an array:
            if (replacement.IsArray)
            {
                // provides deep copies:
                IEnumerable<PhpValue> e = replacement.Array.Values;

                if (deepCopy)
                {
                    e = e.Select(Operators.DeepCopy);
                }

                // does replacement:
                array.ReindexAndReplace(offset, length, e, result);
            }
            else if (replacement.IsNull)
            {
                // replacement is null:

                array.ReindexAndReplace(offset, length, null, result);
            }
            else
            {
                // replacement is another type //

                // creates a deep copy:
                if (deepCopy) replacement = replacement.DeepCopy();

                // does replacement:
                array.ReindexAndReplace(offset, length, new[] { replacement }, result);
            }

            return result;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Creates an array containing range of characters from the [low;high] interval with arbitrary step.
        /// </summary>
        /// <param name="low">Lower bound of the interval.</param>
        /// <param name="high">Upper bound of the interval.</param>
        /// <param name="step">The step.</param>
        /// <returns>The array.</returns>
        /// <exception cref="PhpException">Thrown if the <paramref name="step"/> argument is zero.</exception>
        private static PhpArray RangeOfChars(char low, char high, int step)
        {
            if (step == 0)
            {
                //PhpException.InvalidArgument("step", LibResources.GetString("arg:zero"));
                //step = 1;
                throw new ArgumentException();
            }

            if (step < 0) step = -step;

            PhpArray result = new PhpArray(Math.Abs(high - low) / step + 1, 0);
            if (high >= low)
            {
                for (int i = 0; low <= high; i++, low = unchecked((char)(low + step))) result.Add(i, low.ToString());
            }
            else
            {
                for (int i = 0; low >= high; i++, low = unchecked((char)(low - step))) result.Add(i, low.ToString());
            }

            return result;
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Randomizes the order of elements in the array using PhpMath random numbers generator.
        /// </summary>
        /// <exception cref="PhpException">Thrown if the <paramref name="array"/> argument is null.</exception>
        /// <remarks>Reindexes all keys in the resulting array.</remarks>
        /// <returns>True on success, False on failure.</returns>
        public static bool shuffle(PhpArray array)
        {
            if (array == null)
            {
                //PhpException.ArgumentNull("array");
                //return false;
                throw new ArgumentNullException();
            }

            array.Shuffle(PhpMath.Generator);
            array.ReindexAll();

            return true;
        }
Ejemplo n.º 26
0
            public override void Accept(PhpArray obj)
            {
                // array (size=COUNT)
                _output.Append(PhpArray.PhpTypeName);
                _output.Append($"({obj.Count}) {{");
                _output.Append(_nl);

                _indent++;

                base.Accept(obj);

                _indent--;
                OutputIndent();
                _output.Append("}");
            }
Ejemplo n.º 27
0
 /// <summary>
 /// Chooses specified number of keys from an array at random.
 /// </summary>
 /// <param name="array">The <see cref="PhpArray"/> from which to choose.</param>
 /// <param name="count">The number of items to choose.</param>
 /// <returns>Either <see cref="PhpArray"/> of chosen keys (<paramref name="count"/> &gt; 1) or a single key.</returns>
 /// <remarks>
 /// Items are chosen uniformly in time <I>O(n)</I>, where <I>n</I> is the number of items in the 
 /// <paramref name="array"/> using conveyor belt sampling. 
 /// </remarks>
 /// <exception cref="NullReferenceException"><paramref name="array"/>  is a <B>null</B> reference.</exception>
 /// <exception cref="PhpException"><paramref name="count"/> is not positive and less 
 /// than the number of items in <paramref name="array"/>. (Warning)</exception>
 public static PhpValue array_rand(PhpArray array, int count = 1)
 {
     if (count == 1)
     {
         var result = new List<PhpValue>(1);
         return RandomSubset(array.Keys, result, count, PhpMath.Generator) ? result[0] : PhpValue.Null;
     }
     else
     {
         var result = new PhpArray(count > 0 ? count : 0);
         if (RandomSubset(array.Keys, result, count, PhpMath.Generator))
         {
             //result.InplaceCopyOnReturn = true;
             return PhpValue.Create(result);
         }
         else
         {
             return PhpValue.Null;
         }
     }
 }
Ejemplo n.º 28
0
        internal static PhpArray GetTimeOfDay(System_DateTime utc, TimeZoneInfo/*!*/ zone)
        {
            var result = new PhpArray(0, 4);

            var local = TimeZoneInfo.ConvertTime(utc, zone);

            //int current_dst = 0;
            if (zone.IsDaylightSavingTime(local))
            {
                // TODO: current_dst
                //var rules = zone.GetAdjustmentRules();
                //for (int i = 0; i < rules.Length; i++)
                //{
                //    if (rules[i].DateStart <= local && rules[i].DateEnd >= local)
                //    {
                //        current_dst = (int)rules[i].DaylightDelta.TotalHours;
                //        break;
                //    }
                //}
            }

            const int ticks_per_microsecond = (int)TimeSpan.TicksPerMillisecond / 1000;

            result["sec"] = PhpValue.Create(DateTimeUtils.UtcToUnixTimeStamp(utc));
            result["usec"] = PhpValue.Create((int)(local.Ticks % TimeSpan.TicksPerSecond) / ticks_per_microsecond);
            result["minuteswest"] = PhpValue.Create((int)(utc - local).TotalMinutes);
            //result["dsttime"] = PhpValue.Create(current_dst);

            return result;
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Checks if a key exists in the array.
        /// </summary>
        /// <param name="key">The key to be searched for.</param>
        /// <param name="array">The array where to search for the key.</param>
        /// <returns>Whether the <paramref name="key"/> exists in the <paramref name="array"/>.</returns>
        /// <remarks><paramref name="key"/> is converted before the search.</remarks>
        /// <exception cref="PhpException"><paramref name="array"/> argument is a <B>null</B> reference (Warning).</exception>
        /// <exception cref="PhpException"><paramref name="key"/> has type which is illegal for array key.</exception>
        public static bool array_key_exists(IntStringKey key, PhpArray array)
        {
            if (array == null)
            {
                // TODO: PhpException.ArgumentNull("array");
                return false;
            }

            return array.ContainsKey(key);

            //if (Core.Convert.ObjectToArrayKey(key, out array_key))
            //    return array.ContainsKey(array_key);

            //PhpException.Throw(PhpError.Warning, CoreResources.GetString("illegal_offset_type"));
            //return false;
        }
Ejemplo n.º 30
0
        static PhpValue preg_replace(Context ctx, string pattern, string replacement, PhpCallable callback, PhpValue subject, int limit, ref long count)
        {
            var regex = new PerlRegex.Regex(pattern);

            // TODO: count
            // TODO: callback

            var subject_array = subject.AsArray();
            if (subject_array == null)
            {
                return PhpValue.Create(regex.Replace(subject.ToStringOrThrow(ctx), replacement, limit));
            }
            else
            {
                var arr = new PhpArray(subject_array, false);
                var enumerator = arr.GetFastEnumerator();
                while (enumerator.MoveNext())
                {
                    var newvalue = regex.Replace(enumerator.CurrentValue.ToStringOrThrow(ctx), replacement, limit);
                    enumerator.CurrentValue = PhpValue.Create(newvalue);
                }

                return PhpValue.Create(arr);
            }
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Alias of <see cref="array_key_exists"/>.
 /// </summary>
 public static bool key_exists(IntStringKey key, PhpArray array) => array_key_exists(key, array);
Ejemplo n.º 32
0
 public static int preg_match(Context ctx, string pattern, string subject, out PhpArray matches, int flags = 0, long offset = 0)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 33
0
 /// <summary>
 /// Checks if a value exists in an array.
 /// </summary>
 /// <param name="needle">The value to search for.</param>
 /// <param name="haystack">The <see cref="PhpArray"/> where to search.</param>
 /// <param name="strict">Whether strict comparison method (operator ===) is used for comparing values.</param>
 /// <returns>Whether there is the <paramref name="needle"/> value in the <see cref="PhpArray"/>.</returns>
 /// <exception cref="PhpException"><paramref name="haystack"/> is a <B>null</B> reference (Warning).</exception>
 public static bool in_array(PhpValue needle, PhpArray haystack, bool strict = false)
 {
     var b = array_search(needle, haystack, strict);
     return !b.IsBoolean || b.Boolean;
 }
Ejemplo n.º 34
0
        public static PhpArray preg_grep(Context ctx, string pattern, PhpArray input, int flags = 0)
        {
            if (input == null)
            {
                return null;
            }

            var result = new PhpArray(input.Count);

            if (input.Count != 0)
            {
                var regex = new PerlRegex.Regex(pattern);

                var enumerator = input.GetFastEnumerator();
                while (enumerator.MoveNext())
                {
                    var str = enumerator.CurrentValue.ToStringOrThrow(ctx);
                    var m = regex.Match(str);

                    // move a copy to return array if success and not invert or
                    // not success and invert
                    if (m.Success ^ (flags & PREG_GREP_INVERT) != 0)
                    {
                        result.Add(enumerator.CurrentKey, enumerator.CurrentValue.DeepCopy());
                    }
                }
            }

            //
            return result;
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Searches the array for a given value and returns the corresponding key if successful.
        /// </summary>
        /// <param name="needle">The value to search for.</param>
        /// <param name="haystack">The <see cref="PhpArray"/> where to search.</param>
        /// <param name="strict">Whether strict comparison method (operator ===) is used for comparing values.</param>
        /// <returns>The key associated with the <paramref name="needle"/> or <B>false</B> if there is no such key.</returns>
        /// <exception cref="PhpException"><paramref name="haystack"/> is a <B>null</B> reference (Warning).</exception>
        public static PhpValue array_search(PhpValue needle, PhpArray haystack, bool strict = false)
        {
            // result needn't to be deeply copied because it is a key of an array //

            if (haystack == null)
            {
                // TODO: PhpException.ArgumentNull("haystack");
                return PhpValue.False;
            }

            // using operator ===:
            if (strict)
            {
                using (var enumerator = haystack.GetFastEnumerator())
                    while (enumerator.MoveNext())
                    {
                        // TODO: dereferences value (because of StrictEquality operator):
                        if (needle.StrictEquals(enumerator.CurrentValue))
                            return PhpValue.Create(enumerator.CurrentKey);
                    }
            }
            else
            {
                // using operator ==:

                using (var enumerator = haystack.GetFastEnumerator())
                    while (enumerator.MoveNext())
                    {
                        // note: comparator manages references well:
                        if (needle.Equals(enumerator.CurrentValue))
                            return PhpValue.Create(enumerator.CurrentKey);
                    }
            }

            // not found:
            return PhpValue.False;
        }
Ejemplo n.º 36
0
 /// <summary>
 /// Create a new context resource from an array of wrapper options.
 /// </summary>
 /// <param name="data">A 2-dimensional array of wrapper options</param>
 /// <param name="registerInCtx">Whether to register this instance in current <see cref="Context"/>. Should be <c>false</c> for static resources.</param>
 private StreamContext(PhpArray data, bool registerInCtx)
     : base(StreamContextTypeName/*, registerInCtx*/)
 {
     _data = data;
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Copy constructor. Creates <see cref="PhpArray"/> that shares internal data table with another <see cref="PhpArray"/>.
 /// </summary>
 /// <param name="array">Table to be shared.</param>
 /// <param name="preserveMaxInt">True to copy the <see cref="PhpHashtable.MaxIntegerKey"/> from <paramref name="array"/>.
 /// Otherwise the value will be recomputed when needed. See http://phalanger.codeplex.com/workitem/31484 for more details.</param>
 public PhpArray(PhpArray /*!*/ array, bool preserveMaxInt)
     : base(array, preserveMaxInt)
 {
 }